Replace the Last or Nth occurrence in String in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
5 min

banner

# Table of Contents

  1. Replace the Last occurrence of Substring in String in Python
  2. Replace Nth occurrence of Substring in String in Python

# Replace the Last occurrence of Substring in String in Python

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

  1. Use the str.rsplit() method to split the string on the substring, once, from the right.
  2. Use the str.join() method to join the list with the replacement string as the separator.
main.py
my_str = 'one two two' def replace_last(string, old, new): return new.join(string.rsplit(old, 1)) # ๐Ÿ‘‡๏ธ one two three print(replace_last(my_str, 'two', 'three')) new_str = 'three'.join(my_str.rsplit('two', 1)) print(new_str) # ๐Ÿ‘‰๏ธ one two three

replace last occurrence of substring in string

The code for this article is available on GitHub

The first step is to use the str.rsplit() method to split the string into a list, once, from the right.

main.py
my_str = 'one two two' # ๐Ÿ‘‡๏ธ ['one two ', ''] print(my_str.rsplit('two', 1))

The str.rsplit() method returns a list of the words in the string using the provided separator as the delimiter string.

main.py
my_str = 'bobby hadz com' print(my_str.rsplit(' ')) # ๐Ÿ‘‰๏ธ ['bobby', 'hadz', 'com'] print(my_str.rsplit(' ', 1)) # ๐Ÿ‘‰๏ธ ['bobby hadz', 'com']

The method takes the following 2 arguments:

NameDescription
separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt most maxsplit splits are done, the rightmost ones (optional)

Except for splitting from the right, rsplit() behaves like split().

The last step is to use the str.join() method to join the list into a string with the replacement as the separator.

main.py
my_str = 'one two two' new_str = 'three'.join(my_str.rsplit('two', 1)) print(new_str) # ๐Ÿ‘‰๏ธ one two three

The str.join() method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

The string the method is called on is used as the separator between the elements.

If the substring is not found in the string, the string is returned as is.

main.py
my_str = 'bobbyhadz.com' new_str = 'three'.join(my_str.rsplit('two', 1)) print(new_str) # ๐Ÿ‘‰๏ธ bobbyhadz.com

Alternatively, you can use the str.rfind() method.

# Replace Last occurrence of Substring in String using rfind()

This is a two-step process:

  1. Use the str.rfind() method to get the index of the last occurrence of the substring.
  2. Use string slicing to replace the last occurrence of the substring in the string.
main.py
def replace_last(string, old, new): if old not in string: return string index = string.rfind(old) return string[:index] + new + string[index+len(old):] # ๐Ÿ‘‡๏ธ one two three print(replace_last('one two two', 'two', 'three')) # ๐Ÿ‘‡๏ธ 'abc _ 123' print(replace_last('abc abc 123', 'abc', '_'))

replace last occurrence of substring in string using rfind

The code for this article is available on GitHub

We first check if the substring is not found in the string, in which case we return the string as is.

We used the str.rfind() method to get the index of the last occurrence of the substring in the string.

The str.rfind() method returns the highest index in the string where the provided substring is found.

main.py
print('abc abc 123'.rfind('abc')) # ๐Ÿ‘‰๏ธ 4

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

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

main.py
def replace_last(string, old, new): if old not in string: return string index = string.rfind(old) return string[:index] + new + string[index+len(old):] # ๐Ÿ‘‡๏ธ one two three print(replace_last('one two two', 'two', 'three')) # ๐Ÿ‘‡๏ธ 'abc _ 123' print(replace_last('abc abc 123', 'abc', '_'))

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

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

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

main.py
def replace_last(string, old, new): if old not in string: return string index = string.rfind(old) return string[:index] + new + string[index+len(old) - 1:] # ๐Ÿ‘‡๏ธ bobbyhadz.com print(replace_last('bobbyhadz.com', 'two', 'three'))

# 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
The code for this article is available on GitHub

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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev