Replace first occurrence of a substring in Python

In this article, we will discuss different ways to replace the first occurrence of a substring from a string in Python.

Suppose we have a string,

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

In this string, the substring “is” occurs at 3 different places. But we want to replace only the first occurrence of substring “is” with “XX”. After replacement, the final string should be like,

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

There are different ways to replace only the first occurrence of a substring in string. Let’s discuss them one by one.

Using replace() function

In Python, the string class provides a function replace() to change the content of a string. It’s syntax is as follows,

replace(substring, replacement, count)

Parameters:

  • substring: The substring that need to be replaced in the string.
  • replacement: The replacement string. By which the substring will be replaced.
  • count: The maximumn number of occurrences to replace.

It replaces the count number of occurrences of given substring with the replacement string. A string is immutable in Python, therefore the replace() function returns a copy of the string with modified content.

To replace only first occurrence of “is” with “XX”, pass the count value as 1.

For example:

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

# Replace first occurrence of substring 'is' with 'XX' in the string
strValue = strValue.replace('is', 'XX', 1)

print(strValue)

Output:

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

It replaced the first occurrence of “is” with “XX” in the string.

Using Regex

The regex module in Python provides a function sub() to replace the contents of a string based on a matching regex pattern. The signature of function is like this,

sub(pattern, replacement_str, original_str, count=N)

It looks for the matches of the given regex pattern in the sting original_str and replaces N occurrences of substrings that matches with the replacement string i.e. replacement_str.

We can use this to replace only first occurrence of “is” with “XX”. For that we need to pass the count parameter as 1.

For example:

import re

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

# Replace first occurrence of substring 'is' with 'XX' in the string
strValue = re.sub('is', 'XX', strValue, count=1 )

print(strValue)

Output:

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

It replaced the first occurrence of “is” with “XX” in the string.

Summary:

We learned about two different ways to replace this first occurrence 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