How do you replace multiple substrings in a string in python?

How do you replace multiple substrings in a string in python?

Sometimes, we want to replace multiple substrings of a string in Python.

In this article, we’ll look at how to replace multiple substrings of a string in Python.

How to replace multiple substrings of a string in Python?

To replace multiple substrings of a string in Python, we can use the Python string’s `replace method.

For instance, we write:

def replace_all(text, dic):
    for i, j in dic.items():
        text = text.replace(i, j)
    return text

d = { "cat": "dog", "dog": "pig"}
my_sentence = "This is my cat and this is my dog."
new_sentence = replace_all(my_sentence, d)
print(new_sentence)    

to create the replace_all function.

We loop through the dic dictionary’s key-value pairs which are returned by dic.items.

Then we call text.replace with i and j, which is the original substring and the replacement substring respectively.

And we assign the new returned string to text.

Finally, we return text which has all the replacements done.

Next, we call replace_all with my_sentence and d.

And new_sentence is 'This is my pig and this is my pig.'.

Conclusion

To replace multiple substrings of a string in Python, we can use the Python string’s `replace method.

Web developer specializing in React, Vue, and front end development.

View Archive

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

Table of Contents:

  • Replace multiple characters in a string using the replace()
  • Replace multiple characters in a string using the translate ()
  • Replace multiple characters in a string using regex
  • Replace multiple characters in a string using for loop

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,

Advertisements

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.

How do you replace multiple items in a string in Python?

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.

How do I replace multiple characters in a string?

Use the replace() method to replace multiple characters in a string, e.g. str. replace(/[. _-]/g, ' ') . The first parameter the method takes is a regular expression that can match multiple characters.

How do you replace multiple elements in a list in Python?

One way that we can do this is by using a for loop. One of the key attributes of Python lists is that they can contain duplicate values. Because of this, we can loop over each item in the list and check its value. If the value is one we want to replace, then we replace it.

How do you replace all occurrences of a string in Python?

The replace() method replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.