This post shows you how to replace the last occurrence of a string in Python.
For example, we want to replace the last occurrence of the
Bar string with
guys string in the following string.
Foo and Bar. Hello Bar.
The result should become
Foo and Bar. Hello guys.
One of the ideas to do this in Python is that we will reverse the string using this
[::-1] slicing syntax and then use
string.replace() method to replace the first occurrence of the
Bar string on the reversed string. Finally, use
[::-1] slicing syntax again to reverse the replaced string.
def replace_last(string, find, replace): reversed = string[::-1] replaced = reversed.replace(find[::-1], replace[::-1], 1) return replaced[::-1]
result = replace_last("Hello World, Hello World.", "Hello", "Hi") print(result)
In the above code, we replace the last occurrence of the
Hello string with
Hi string. The result we get is:
Hello World, Hi World.