Replace multiple substrings of a string in Python

When working with strings in Python programming, it’s often necessary to replace one or more substrings within a larger string with a new substring. This can be a tedious and time-consuming task if done manually, but fortunately, there are many ways to automate the process.

In this article, we will explore several methods for replacing multiple substrings in a string in Python. From using the replace() method to regular expressions and translation tables, we’ll cover a variety of approaches that can help make your string manipulation tasks more efficient and less error-prone.

1. Using the replace() method with a loop

You can iterate over a list of substrings to be replaced and use the replace() method to replace each substring with the desired new substring. Here’s an example code snippet:

string = "This is a sample string"
subs_to_replace = ["is", "sample"]
new_subs = ["was", "example"]

for i in range(len(subs_to_replace)):
    string = string.replace(subs_to_replace[i], new_subs[i])

print(string)

2. Using a dictionary to map substrings

You can create a dictionary where the keys are the substrings to be replaced and the values are the new substrings. Then, you can use the sub() method from the regular expression module to replace all occurrences of the substrings in the string. Here’s an example code snippet:

import re

string = "This is a sample string"
subs_to_replace = {"is": "was", "sample": "example"}

pattern = re.compile("|".join(map(re.escape, subs_to_replace.keys())))
new_string = pattern.sub(lambda match: subs_to_replace[match.group()], string)

print(new_string)

3. Using the translate() method

You can create a translation table using the maketrans() method and then use the translate() method to replace all occurrences of the substrings in the string. Here’s an example code snippet:

string = "This is a sample string"
subs_to_replace = {"is": "was", "sample": "example"}

translation_table = str.maketrans(subs_to_replace)
new_string = string.translate(translation_table)

print(new_string)

4. Using a regular expression pattern with re.sub()

You can use a regular expression pattern to match multiple substrings to be replaced and replace them with the desired new substrings using the re.sub() method. Here’s an example code snippet:

import re

string = "This is a sample string"
replacements = {"is": "was", "sample": "example"}

pattern = re.compile("|".join(re.escape(k) for k in replacements))
new_string = pattern.sub(lambda match: replacements[match.group()], string)

print(new_string)

5. Using the str.replace() method with tuple unpacking

You can pass the substrings to be replaced and their corresponding replacements as a tuple to the str.replace() method using tuple unpacking. Here’s an example code snippet:

string = "This is a sample string"
replacements = [("is", "was"), ("sample", "example")]

for old, new in replacements:
    string = string.replace(old, new)

print(string)

6. Using a list comprehension

You can use a list comprehension to replace all occurrences of multiple substrings in a string.

string = "This is a sample string"
replacements = {"is": "was", "sample": "example"}

new_string = "".join([replacements.get(c, c) for c in string])

print(new_string)

Summary and Conclusion

Replacing multiple substrings in a string is a common task in programming. In this article, we explored six different methods for replacing multiple substrings in a string in Python. I hope this article was helpful.

Leave a Comment

Scroll to Top