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
For the second example, I would recommend rsplit
, as it is very simple to use and and directly achieves the goal. Here is a little function with it:
def replace_ending(sentence, old, new):
if sentence.endswith(old):
i = sentence.rsplit(old,1)
new_sentence =new.join(i)
return new_sentence
return sentence
print(replace_ending("aaa bbb aaa bbb", "bbb", "xxx"))
Output:
aaa bbb aaa xxx