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

python, string

Solution

>>> def rreplace(s, old, new, occurrence):
...  li = s.rsplit(old, occurrence)
...  return new.join(li)
... 
>>> s
'1232425'
>>> rreplace(s, '2', ' ', 2)
'123 4 5'
>>> rreplace(s, '2', ' ', 3)
'1 3 4 5'
>>> rreplace(s, '2', ' ', 4)
'1 3 4 5'
>>> rreplace(s, '2', ' ', 0)
'1232425'

Problem

Is there a quick way in Python to replace strings but, instead of starting from the beginning as `replace` does, starting from the end? For example: ``` >>> def rreplace(old, new, occurrence) >>> ... # Code to replace the last occurrences of old by new >>> '<div><div>Hello</div></div>'.rreplace('</div>','</bad>',1) >>> '<div><div>Hello</div></bad>' ```

Original source