How to replace the some characters from the end of a string?

后端 未结 8 1405
迷失自我
迷失自我 2021-02-03 21:34

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

8条回答
  •  情歌与酒
    2021-02-03 22:06

    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

提交回复
热议问题