Python: Replace multiple characters in a string

In this article, we will discuss different ways to replace multiple characters in a string in Python.

Table of Contents:

Suppose we have a string,

sample_string = "This is a sample string"

Now we want the following characters to be replaced in that string,

  • Replace all occurrences of ‘s’ with ‘X’.
  • Replace all occurrences of ‘a’ with ‘Y’.
  • Replace all occurrences of ‘i’ with ‘Z’.
  • Python: Replace multiple characters in a string using for loop

There are different ways to do this. Let’s discuss them one by one,

Python: Replace multiple characters in a string using the replace()

In Python, the String class (Str) provides a method replace(old, new) to replace the sub-strings in a string. It replaces all the occurrences of the old sub-string with the new sub-string.

In Python, there is no concept of a character data type. A character in Python is also a string. So, we can use the replace() method to replace multiple characters in a string.

sample_string = "This is a sample string"

char_to_replace = {'s': 'X',
                   'a': 'Y',
                   'i': 'Z'}

# Iterate over all key-value pairs in dictionary
for key, value in char_to_replace.items():
    # Replace key character with value character in string
    sample_string = sample_string.replace(key, value)

print(sample_string)

Output:

ThZX ZX Y XYmple XtrZng

It replaced all the occurrences of,

  • Character ‘s’ with ‘X’.
  • Character ‘a’ with ‘Y’.
  • Character ‘i’ with ‘Z’.

As strings are immutable in Python and we cannot change its contents. Therefore, replace() function returns a copy of the string with the replaced content.

Python: Replace multiple characters in a string using the translate ()

We can also replace multiple characters in string with other characters using translate() function,

sample_string = "This is a sample string"

char_to_replace = {'s': 'X',
                   'a': 'Y',
                   'i': 'Z'}

# Replace all multiple characters in a string
# based on translation table created by dictionary
sample_string = sample_string.translate(str.maketrans(char_to_replace))

print(sample_string)

Output:

ThZX ZX Y XYmple XtrZng

We created that translation table from a dictionary using Str.maketrans() function. We then passed that translation table as an argument to the translate() method of Str, which replaced following characters in string based on that translation table,

  • Character ‘s’ gets replaced with ‘X’.
  • Character ‘a’ gets replaced with ‘Y’.
  • Character ‘i’ gets replaced with ‘Z’.

As strings are immutable in Python and we cannot change its contents. Therefore translate() function returns a copy of the string with the replaced content.

Python: Replace multiple characters in a string using regex

Python provides a regex module (re), and in this module, it provides a function sub() to replace the contents of a string based on patterns. We can use this re.sub() function to substitute/replace multiple characters in a string,

import re

sample_string = "This is a sample string"

char_to_replace = {'s': 'X',
                   'a': 'Y',
                   'i': 'Z'}

# Replace multiple characters (s, a and i) in string with values in
# dictionary using regex
sample_string = re.sub(r"[sai]",
                       lambda x: char_to_replace[x.group(0)],
                       sample_string)

print(sample_string)

Output:

ThZX ZX Y XYmple XtrZng

Here we passed a pattern r’[sai]’ as the first argument, which matches all occurrences of character ‘s’, ‘a’ and ‘i’. As the second argument in the sub() function, we passed a lambda function, which fetches the matched character from the match object and then returns the value associated with it from the dictionary. Then as the third argument, we passed the original string.

Now for each character in the string that matches the pattern, it calls the lambda function, which gives the replacement character. Then the sub() function replaces that character in the string.

It replaced all the occurrences of,

  • Character ‘s’ with ‘X’.
  • Character ‘a’ with ‘Y’.
  • Character ‘i’ with ‘Z’.

As strings are immutable in Python and we cannot change its contents. Therefore sub() function of the regex module returns a copy of the string with the replaced content.

Python: Replace multiple characters in a string using for loop

Initialize a new empty string and then iterate over all characters of the original string. During iteration, for each check, if the character exists in the dictionary char_to_replaced or not,

  • If yes, the fetch replacement of that character and add to the new string.
  • If no, then add the character to the new string.

For example,

sample_string = "This is a sample string"

char_to_replace = {'s': 'X',
                   'a': 'Y',
                   'i': 'Z'}

result = ''
# Iterate over all characters in string
for elem in sample_string:
    # Check if character is in dict as key
    if elem in char_to_replace:
        # If yes then add the value of that char
        # from dict to the new string
        result += char_to_replace[elem]
    else:
        # If not then add the character in new string
        result += elem

print(result)

Output:

ThZX ZX Y XYmple XtrZng

It replaced all the occurrences of,

  • Character ‘s’ with ‘X’.
  • Character ‘a’ with ‘Y’.
  • Character ‘i’ with ‘Z’.

As strings are immutable in Python and we cannot change its contents. Therefore, we created a new copy of the string with the replaced content.

Summary

We can replace multiple characters in a string using replace() , regex.sub(), translate() or for loop in python.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top