Replace Nth occurrence of Substring in String in Python

avatar

Borislav Hadzhiev

Last updated: Sep 23, 2022

banner

Photo from Unsplash

Replace Nth occurrence of Substring in String in Python #

To replace the Nth occurrence of a substring in a string:

  1. Find the index of the Nth occurrence of the substring in the string.
  2. Use string slicing to replace the Nth occurrence of the substring.
  3. If the substring is not contained N times in the string, return the string as is.
main.py
def replace_nth(string, old, new, n): index_of_occurrence = string.find(old) occurrence = int(index_of_occurrence != -1) print(occurrence) # 👇️ find index of Nth occurrence while index_of_occurrence != -1 and occurrence != n: index_of_occurrence = string.find(old, index_of_occurrence + 1) occurrence += 1 # 👇️ index of Nth occurrence found, replace substring if occurrence == n: return ( string[:index_of_occurrence] + new + string[index_of_occurrence+len(old):] ) # 👇️ if N occurrences of substring not found in string, return string return string my_str = 'one one one two' new_str = replace_nth(my_str, 'one', '_', 1) print(new_str) # 👉️ _ one one two new_str = replace_nth(my_str, 'one', '_', 2) print(new_str) # 👉️ one _ one two new_str = replace_nth(my_str, 'one', '_', 3) print(new_str) # 👉️ one one _ two new_str = replace_nth(my_str, 'one', '_', 100) print(new_str) # 👉️ one one one two new_str = replace_nth(my_str, 'abc', '_', 100) print(new_str) # 👉️ one one one two

We used the str.find() method to find the index of the first occurrence of the substring in the string.

The str.find method returns the index of the first occurrence of the provided substring in the string.

The method returns -1 if the substring is not found in the string.

If the str.find() method doesn't return -1, then the substring is contained at least once in the string.

The str.rfind() method can be passed a start index argument to start looking for a substring after the specified index.

The purpose of the while loop is to iterate until it finds the Nth occurrence of the substring in the string.

main.py
while index_of_occurrence != -1 and occurrence != n: index_of_occurrence = string.find(old, index_of_occurrence + 1) occurrence += 1
If the str.find() method returns -1 and the occurrences variable is not set to n, then the substring is not contained N times in the string.

If the occurrence variable gets set to n, then we have found the index of the Nth occurrence of the substring in the string.

main.py
if occurrence == n: return ( string[:index_of_occurrence] + new + string[index_of_occurrence+len(old):] )

In this case, we use string slicing to replace the substring.

The slice string[:index_of_occurrence] starts at index 0 and goes up to, but not including the index of the Nth occurrence of the substring.

We used the addition (+) operator to append the replacement string.

The slice string[index_of_occurrence+len(old):] starts at the index after the last character of the Nth occurrence of the substring that is to be replaced.

If the substring is not contained in the string N times, we return the string as is.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.