Python – Replace Last Occurrence of a String

This post shows you how to replace the last occurrence of a string in Python.
 

1. Explanation

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.

 

2. Implementation

string_example.py
def replace_last(string, find, replace):
    reversed = string[::-1]
    replaced = reversed.replace(find[::-1], replace[::-1], 1)
    return replaced[::-1]

 

3. Example

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.

guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x