Replace all occurrences of a substring in string – Python

In this article, we will discuss different ways to replace all occurrences of a given substring in a string in Python.

Suppose we have a string,

"This is the last rain of Season and Jack is here."

After replacing all occurrences of “is” with with the “XX”, the final string should be like,

"ThXX XX the last rain of Season and Jack XX here."

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

Using replace() function

The replace(to_be_replaced, replacement) function of string class in Python, provides a direct way to replace all occurrences of a substring with another string in the calling string object.

We can use this to replace all occurrences of “is” with “XX”, by passing them as arguments to the replace() function.

For Example:

strValue = "This is the last rain of Season and Jack is here."

# Replace all occurrences of substring 'is' in string with 'XX'
strValue = strValue.replace('is', 'XX')

print(strValue)

Output:

ThXX XX the last rain of Season and Jack XX here.

It replaced all occurrences of substring “is” with “XX” in the given string.

Using Regex

The regex module in Python provides a function sub(pattern, replacement_str, original_str) to replace the substrings in a string based on matching regex pattern. All the substrings that matches the given regex pattern in the original string, will be replaced by the replacement string.

We can use this to replace all occurrences of “is” with “XX. For that we need to pass following arguments to regex.sub() function,

  • “is”: A Regex Pattern that matches all the occurrences of substring “is” in the string.
  • “XX”: The replacement string
  • Original String: The strinh in which we need to replace all the occurrences of substring “is”

For Example:

import re

strValue = "This is the last rain of season and Jack is here."

# Replace all occurrences of substring 'is' in string with 'XX'
strValue = re.sub('is', 'XX', strValue )

print(strValue)

Output:

ThXX XX the last rain of Season and Jack XX here.

Strings in Python are immutable. We can modify its contents but we can create a copy of the string with the modified contents.

The regex.sub() function returned a copy of original string with the modified contents. We can assign that back to the original variable. It will give an effect that all occurrences of substring “is” with “XX” in the given string.

Summary:

We learned about two different ways to replace all occurrences of a substring in a string 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