Signup/Sign In
PUBLISHED ON: FEBRUARY 26, 2021

How to replace multiple substrings of a string in Python?

In this article, we will learn to convert a list to a string in Python. We will use some built-in functions and some custom code as well. Let's first have a quick look over what is list and string in Python.

Python String

The String is a type in python language just like integer, float, boolean, etc. Data surrounded by single quotes or double quotes are said to be a string. A string is also known as a sequence of characters.

string1 = "apple"
string2 = "Preeti125"
string3 = "12345"
string4 = "Model number is 56@1"

Replace multiple Substrings in a String using replace()

The below example uses replace() function provided by Python Strings. It replaces all the occurrences of a sub-string to a new string by passing the old and new strings as parameters to the replace() function. Multiple calls to replace() function are required to replace multiple substrings in a string. There is also a third parameter that is optional in replace() which accepts an integer to set the maximum count of replacements to execute.

Example 1

str1 = "Fear leads to anger; anger leads to hatred; hatred leads to conflict"

str2 = str1.replace("anger", "rage")
str3 = str2.replace("to", "2")

print(str3)


Fear leads 2 rage; rage leads 2 hatred; hatred leads 2 conflict

Example: Creates Dictionary of substrings to replace

The below examples create a dictionary of substrings as key-value pairs. Keys represent the sub-string and values are the new strings.

str1 = "Fear leads to anger; anger leads to hatred; hatred leads to conflict"

char_to_replace = {'to': '2', ';': ',', 'anger': 'rage'}

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

print(str1)


Fear leads 2 rage, rage leads 2 hatred, hatred leads 2 conflict

Example

This method uses two functions - translate() and maketrans().

maketrans() - It a mapping table between the original string and its replacement. It is a method of str. It takes two parameters - an old string and a new string.

translate() - It generates the translated string retuned by maketrans() function.

import string

str1 = "Fear leads to anger; anger leads to hatred; hatred leads to conflict"

res = str1.translate(str.maketrans("o", "0"))
print(res)


Fear leads t0 anger; anger leads t0 hatred; hatred leads t0 c0nflict

Example: Replace using Regex module

This method uses regex Python's module. Regex provides multiple string operations based on expressions. We will use two functions of the regex module- re.sub() and re.subn() to replace multiple substrings in a string.

sub() - It replaces the contents of a string based on patterns. It takes a pattern or a string as the first argument. The second argument is the lambda function which extracts the matched sub-string then returns the value associated with it from the dictionary. It takes the original string as the third argument.

subn() - It is similar to the above function but it returns a tuple of the converted string and the number of replacements made. It is useful if you want to note how many pattern groups you manipulated as metrics or for further processing.

Example 1 Use re.sub()

When re.sub() matches pattern from the string, it calls the lambda function, which gives the replacement character, then the sub() function replaces that character in the string.

import re

str1 = "Fear leads to anger; anger leads to hatred; hatred leads to conflict"

str1 = re.sub("leads", lambda x: 'x', str1)

print(str1)


Fear x to anger; anger x to hatred; hatred x to conflict

Example : Use re.subn()

import re

str1 = "Hi, my number is 08999XX. I am 23 years old. I live in 221B Baker Street."

str1, n = re.subn('[0-9]', 'X',str1)

print(str1)


Hi, my number is XXXXXXX. I am XX years old. I live in XXXB Baker Street.

Conclusion

In this article, we learned to replace multiple substrings in a string by using several built-in functions such as re.sub(), re.subn(), str.replace(), str.maketrans(), translate() etc and we used some custom code as well.



About the author:
An enthusiastic fresher, a patient person who loves to work in diverse fields. I am a creative person and always present the work with utmost perfection.