Computer >> Computer tutorials >  >> Programming >> Python

How to remove a list of characters in string in Python?


The string class has a method replace that can be used to replace substrings in a string. We can use this method to replace characters we want to remove with an empty string. For example:

>>> "Hello people".replace("e", "")
"Hllo popl"

If you want to remove multiple characters from a string in a single line, it's better to use regular expressions. You can separate multiple characters by "|" and use the re.sub(chars_to_replace, string_to_replace_with, str). For example:

>>> import re
>>> re.sub("e|l", "", "Hello people")
"Ho pop"

If you already have the characters you want to remove in a list, you can use join() to create the regex as well. For Example,

>>> import re
>>> char_list = ['a', 'e', 'i', 'o', 'u']
>>> re.sub("|".join(char_list), "", "Hello people")
"Hll ppl"

Note: You can also use the [] to create group of characters to replace in regex.