Remove multiple characters from string Python | Example code

You can use replace() method or re.sub() to remove multiple characters from the string in Python.

Example How to Remove multiple characters from string Python

Simple example code.

Use replace() method

Use a for-loop to iterate through each character and call str.replace(old, new) with old as the character and new as “” to replace it.

a_string = "!(Hello World)@"

remove = "!()@"

for char in remove:
    a_string = a_string.replace(char, "")



Remove multiple characters from string Python

Use re.sub()

Use string concatenation to add “[” to the front of the string of multiple characters and “[” to the back of the string. Call re.sub(pattern, replace, string) with a pattern.

You have to import the “re” module for it.

import re

a_string = "!(Hello World)@"

remove = "!()@"

pattern = "[" + remove + "]"
new_string = re.sub(pattern, "", a_string)


Output: Hello World

Do comment if you have any doubts and suggestions on this Python char code.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.