Replace last occurrence of Substring in String in Python

avatar

Borislav Hadzhiev

Last updated: Sep 23, 2022

banner

Photo from Unsplash

Replace 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

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() #

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

  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', '_'))

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'))

Which approach you pick is a matter of personal preference. I'd go with using the str.rsplit() and str.join() methods for readability purposes.

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.