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
When the wanted match is at the end of string, re.sub comes to the rescue.
>>> import re
>>> s = "aaa bbb aaa bbb"
>>> s
'aaa bbb aaa bbb'
>>> re.sub('bbb$', 'xxx', s)
'aaa bbb aaa xxx'
>>>
This is one of the few string functions that doesn't have a left and right version, but we can mimic the behaviour using some of the string functions that do.
>>> s = '123123'
>>> t = s.rsplit('2', 1)
>>> u = 'x'.join(t)
>>> u
'1231x3'
or
>>> 'x'.join('123123'.rsplit('2', 1))
'1231x3'