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
This is exactly what the rpartition
function is used for:
rpartition(...) S.rpartition(sep) -> (head, sep, tail)
Search for the separator sep in S, starting at the end of S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return two empty strings and S.
I wrote this function showing how to use rpartition
in your use case:
def replace_last(source_string, replace_what, replace_with):
head, _sep, tail = source_string.rpartition(replace_what)
return head + replace_with + tail
s = "123123"
r = replace_last(s, '2', 'x')
print r
Output:
1231x3