I want to replace characters at the end of a python string. I have this string:
s = "123123"
I want to replace the last 2 with x. Suppose there is a method called replace_last:
>>> replace_last(s, '2', 'x')
'1231x3'
Is there any built-in or easy method to do this?
It’s similar to python’s str.replace():
>>> s.replace('2', 'x', 1)
'1x3123'
But it’s from the end to beginning.
This is exactly what the
rpartitionfunction is used for:I wrote this function showing how to use
rpartitionin your use case:Output: