Replace Multiple Characters in a String in Python
To replace multiple characters in a string in Python we will need to use the .replace()
method in a custom function that iterates over each char to remove.
Python Replace Multiple Chars in String Function
The example function below accepts two arguments, the string to modify and the characters to remove. The function iterates over each character to remove and applies it to the string using the .replace()
method.
def removeChars(string, chars = ''):
for c in chars:
string = string.replace(c, '')
return string
string = 'Hello#- World!'
chars = '#-!'
res = removeChars(string, chars)
print(res)
Hello World
Replace Multiple Characters Using re.sub in Python
The Python re
package contains the sub-method for modifying characters in a string using regex. We can use the regex character group utility ([]
) inside a literal string (r""
) to remove multiple characters in one hit. This makes it a cleaner solution than using .replace()
in a for loop.
import re
string = 'Hello#- World!'
res = re.sub(r"[!?#-]", '', string)
print(res)
Hello World
The above example remove all !?#-
characters from the given string.
Here is a reusable character replace function using re.sub
, which accepts a string, chars to replace and what to replace them with:
import re
def removeChars(string, chars = '', replace = ''):
return re.sub(r"["+chars+"]", replace, string)
string = 'Hello#- World!'
chars = '!?#-'
replace = ''
res = removeChars(string, chars, replace)
print(res)
Hello World