Last updated: Apr 10, 2024
Reading timeยท4 min
Use multiple calls to the str.replace()
method to replace multiple
characters in a string.
The str.replace()
method returns a new string with the specified substring
replaced and can be called as many times as necessary.
string = 'bobby!hadz@com' string = string.replace('!', '-').replace('@', '_') print(string) # ๐๏ธ bobby-hadz_com
The example chains multiple calls to the str.replace()
method to replace
multiple characters in a string.
The str.replace() method returns a copy of the string with all occurrences of a substring replaced by the provided replacement.
string = 'bobby!hadz@com' # ๐๏ธ bobby-hadz@com print(string.replace('!', '-')) # ๐๏ธ bobby-hadz_com print(string.replace('!', '-').replace('@', '_'))
The method takes the following parameters:
Name | Description |
---|---|
old | The substring we want to replace in the string |
new | The replacement for each occurrence of old |
count | Only the first count occurrences are replaced (optional) |
The method doesn't change the original string. Strings are immutable in Python.
str.replace()
method is quite efficient, so if you only have to replace a couple of substrings in the string, this approach works perfectly fine.Alternatively, you can store the characters to be replaced and the replacements in a list.
Here is an example that uses a list of replacements.
for
loop to iterate over the list.str.replace()
method to replace each character in the string.string = 'bobby!hadz@com' replacements = [('!', '-'), ('@', '_')] for char, replacement in replacements: if char in string: string = string.replace(char, replacement) print(string) # ๐๏ธ bobby-hadz_com
We stored the substrings to be replaced and the replacement strings in a list of tuples and used a for loop to iterate over the list.
On each iteration, we check if the character to be replaced is contained in the string.
The in operator tests
for membership. For example, x in s
evaluates to True
if x
is a member of
s
, otherwise it evaluates to False
.
If the condition is met, we replace the character with the provided replacement and reassign the variable.
Alternatively, you can store the replacements in a dictionary.
Here is an example that uses a dictionary of replacements.
for
loop to iterate over the dictionary's items.str.replace()
method to replace each character in the string.string = 'bobby!hadz@com' replacements_dict = { '!': '-', '@': '_' } for key, value in replacements_dict.items(): if key in string: string = string.replace(key, value) print(string) # ๐๏ธ bobby-hadz_com
Each key in the dictionary is a character we want to replace in the string and the values are the replacements.
The dict.items() method returns a new view of the dictionary's items ((key, value) pairs).
replacements_dict = { '!': '-', '@': '_' } # ๐๏ธ dict_items([('!', '-'), ('@', '_')]) print(replacements_dict.items())
We used a for
loop to iterate over the dictionary's items.
On each iteration, we check if the substring is contained in the string.
If the condition is met, we replace the substring with the replacement string and reassign the variable.
You can also use the re.sub()
method to replace multiple characters in a
string with a single character.
import re string = 'bobby!hadz@com#12 34' string = re.sub(r'!|@|#|\s', '_', string) print(string) # ๐๏ธ bobby_hadz_com_12_34
The re.sub() method returns a new string that is obtained by replacing the occurrences of the pattern with the provided replacement.
The first argument we passed to the re.sub()
method is a regular expression.
The pipe |
special character means OR, e.g. X|Y
matches X
or Y
.
The \s
special character matches spaces, tabs and newlines.
The regex replaces !
, @
, #
and whitespace characters with underscores.
Alternatively, you can use the str.translate()
method.
This is a three-step process:
str.maketrans()
method to create a translation map.str.translate()
method to replace the characters.string = 'bobby!hadz@com' replacements_dict = { '!': '-', '@': '_' } string = string.translate(str.maketrans(replacements_dict)) print(string) # ๐๏ธ bobby-hadz_com
str.maketrans()
method can only be passed keys of length 1
.If your keys are longer than 1 character, use the dict.items()
approach.
The
str.maketrans()
method returns a translation table that is used by the str.translate()
method.
string = 'bobby!hadz@com' replacements_dict = { '!': '-', '@': '_' } # ๐๏ธ {33: '-', 64: '_'} print(str.maketrans(replacements_dict))
The method takes a dictionary mapping Unicode integers or characters (strings of
length 1) to Unicode ordinals, strings of arbitrary length or None
.
The method converts the keys in the dictionary to ordinals in a format suitable
for the str.translate()
method.
The str.translate() method returns a copy of the string in which each character has been mapped through the provided translation table.
string = 'bobby!hadz@com' replacements_dict = { '!': '-', '@': '_' } string = string.translate(str.maketrans(replacements_dict)) print(string) # ๐๏ธ bobby-hadz_com
In short, the string.translate()
method maps the ordinals to the corresponding
dictionary values.
This approach is less flexible and more difficult to read than using the
dict.items()
method from the previous subheading.
In most cases, chaining multiple calls to the str.replace()
method should be
sufficient to replace multiple substrings in a string.
You can learn more about the related topics by checking out the following tutorials: