How to replace multiple Characters in a String in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
4 min

banner

# Table of Contents

  1. Replace multiple characters in a String in Python
  2. Replace multiple characters in a String using a list of replacements
  3. Replace multiple characters in a String using a dictionary of replacements
  4. Replace multiple characters in a String using re.sub()
  5. Replace multiple characters in a String using str.translate()

# Replace multiple characters in a String in Python

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.

main.py
string = 'bobby!hadz@com' string = string.replace('!', '-').replace('@', '_') print(string) # ๐Ÿ‘‰๏ธ bobby-hadz_com

replace multiple characters in string

The code for this article is available on GitHub

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.

main.py
string = 'bobby!hadz@com' # ๐Ÿ‘‡๏ธ bobby-hadz@com print(string.replace('!', '-')) # ๐Ÿ‘‡๏ธ bobby-hadz_com print(string.replace('!', '-').replace('@', '_'))

The method takes the following parameters:

NameDescription
oldThe substring we want to replace in the string
newThe replacement for each occurrence of old
countOnly the first count occurrences are replaced (optional)

The method doesn't change the original string. Strings are immutable in Python.

Chaining multiple calls to the 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.

# Replace multiple characters in a String using a list of replacements

Here is an example that uses a list of replacements.

  1. Store the characters to be replaced and the replacements in a list.
  2. Use a for loop to iterate over the list.
  3. Use the str.replace() method to replace each character in the string.
main.py
string = 'bobby!hadz@com' replacements = [('!', '-'), ('@', '_')] for char, replacement in replacements: if char in string: string = string.replace(char, replacement) print(string) # ๐Ÿ‘‰๏ธ bobby-hadz_com

replace multiple characters in string using list of replacements

The code for this article is available on GitHub

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.

# Replace multiple characters in a String using a dictionary of replacements

Here is an example that uses a dictionary of replacements.

  1. Store the characters to be replaced and the replacements in a dictionary.
  2. Use a for loop to iterate over the dictionary's items.
  3. Use the str.replace() method to replace each character in the string.
main.py
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

replace multiple characters in string using dictionary of replacements

The code for this article is available on GitHub

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).

main.py
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.

# Replace multiple characters in a String using re.sub()

You can also use the re.sub() method to replace multiple characters in a string with a single character.

main.py
import re string = 'bobby!hadz@com#12 34' string = re.sub(r'!|@|#|\s', '_', string) print(string) # ๐Ÿ‘‰๏ธ bobby_hadz_com_12_34

replace multiple characters in string using re sub

The code for this article is available on GitHub

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.

# Replace multiple characters in a String using str.translate()

This is a three-step process:

  1. Store the characters to be replaced and the replacements in a dictionary.
  2. Use the str.maketrans() method to create a translation map.
  3. Use the str.translate() method to replace the characters.
main.py
string = 'bobby!hadz@com' replacements_dict = { '!': '-', '@': '_' } string = string.translate(str.maketrans(replacements_dict)) print(string) # ๐Ÿ‘‰๏ธ bobby-hadz_com

replace multiple characters in string using str translate

The code for this article is available on GitHub
Note that the 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.

main.py
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.

main.py
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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev