Remove last occurrence of substring from String in Python

avatar

Borislav Hadzhiev

Last updated: Aug 14, 2022

banner

Photo from Unsplash

Remove last occurrence of substring from String in Python #

To remove the last occurrence of a substring from a string:

  1. Use the str.rsplit() method to split the string once, from the right.
  2. Use the str.join() method to join the list of strings.
  3. The new string won't contain the last occurrence of the provided substring.
main.py
def remove_last_occurrence(string, substring): return ''.join(string.rsplit(substring, 1)) # ✅ remove last occurrence of character from string # 👇️ 'helo' print(remove_last_occurrence('hello', 'l')) # ✅ remove last occurrence of word from string # 👇️ 'test one two' print( remove_last_occurrence('test one test two', 'test ') )

We created a reusable function that takes a string and a substring and removes the last occurrence of the substring from the string.

We used the str.rsplit() method to split the string on the provided substring once, from the right.

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 = 'one two three' print(my_str.rsplit(' ')) # 👉️ ['one', 'two', 'three'] print(my_str.rsplit(' ', 1)) # 👉️ ['one two', 'three'] print('hello'.rsplit('l', 1)) # 👉️ ['hel', 'o'] # 👇️ ['test one ', 'two'] print('test one test two'.rsplit('test ', 1))

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)

We set the maxsplit argument to 1 because we only want to split the string once, from the right.

When we split the string on the provided substring once, from the right, we get a list of strings without the last occurrence of the substring.

The last step is to join the list of strings with an empty string separator.

main.py
def remove_last_occurrence(string, substring): return ''.join(string.rsplit(substring, 1)) # 👇️ 'helo' print(remove_last_occurrence('hello', 'l')) # 👇️ 'test one two' print( remove_last_occurrence('test one test two', 'test ') )

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.

For our purposes, we called the method on an empty string to join the list of strings without a separator.

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.