There is a way to handle replace
to make it work backwards.
The idea is to reverse the string, text to replace and new text using [::-1]
. The logic stays the same.
For example:
>>> a = "123 456 123 456 123 456"
and we want to replace the last one, (or two, or n) occurrences of "123" with "abc"
>>> a[::-1].replace("123"[::-1], "abc"[::-1], 1)[::-1]
'123 456 123 456 abc 456'
This could be put as a function that behaves exactly like replace.
def replace_right(text, old, new, count=-1):
"""
Return a copy of text with all occurrences of substring old
replaced by new, starting from the right.
If count is given and is not -1, only the first count
occurrences are replaced.
"""
return text[::-1].replace(old[::-1], new[::-1], count)[::-1]
Execution:
>>> replace_right(a, "123", "abc", 1)
'123 456 123 456 abc 456'
>>> replace_right(a, "123", "abc", 2)
'123 456 abc 456 abc 456'