Skip to content

Remove multiple characters from string Python | Example code

  • by

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, "")

print(a_string)

Output:

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)

print(new_string)

Output: Hello World

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

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Your email address will not be published. Required fields are marked *