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.
Pandas Tutorials -Learn Data Analysis with Python
-
Pandas Tutorial Part #1 - Introduction to Data Analysis with Python
-
Pandas Tutorial Part #2 - Basics of Pandas Series
-
Pandas Tutorial Part #3 - Get & Set Series values
-
Pandas Tutorial Part #4 - Attributes & methods of Pandas Series
-
Pandas Tutorial Part #5 - Add or Remove Pandas Series elements
-
Pandas Tutorial Part #6 - Introduction to DataFrame
-
Pandas Tutorial Part #7 - DataFrame.loc[] - Select Rows / Columns by Indexing
-
Pandas Tutorial Part #8 - DataFrame.iloc[] - Select Rows / Columns by Label Names
-
Pandas Tutorial Part #9 - Filter DataFrame Rows
-
Pandas Tutorial Part #10 - Add/Remove DataFrame Rows & Columns
-
Pandas Tutorial Part #11 - DataFrame attributes & methods
-
Pandas Tutorial Part #12 - Handling Missing Data or NaN values
-
Pandas Tutorial Part #13 - Iterate over Rows & Columns of DataFrame
-
Pandas Tutorial Part #14 - Sorting DataFrame by Rows or Columns
-
Pandas Tutorial Part #15 - Merging or Concatenating DataFrames
-
Pandas Tutorial Part #16 - DataFrame GroupBy explained with examples
Are you looking to make a career in Data Science with Python?
Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.
Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.
Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.