How to replace the last occurrence of an expression in a string in Python?


This problem can be solved by reversing the string, reversing the string to be replaced,replacing the string with reverse of string to be replaced with and finally reversing the string to get the result. 

You can reverse strings by simple slicing notation - [::-1]. To replace the string you can use str.replace(old, new, count). For example,

 def rreplace(s, old, new):
    return (s[::-1].replace(old[::-1],new[::-1], 1))[::-1]
 rreplace('Helloworld, hello world, hello world', 'hello', 'hi')

 This will give the output:

'Hello world,hello world, hi world'

Another method by which you can do this is to reverse split the string once on the old string and join the list with the new string. For example,

 def rreplace(s, old, new):
    li = s.rsplit(old, 1) #Split only once
    return new.join(li)
 rreplace('Helloworld, hello world, hello world', 'hello', 'hi')

 This will give the output:

'Hello world, hello world, hi world'

 

Updated on: 30-Sep-2019

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements