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

后端 未结 8 1400
迷失自我
迷失自我 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:22

    >>> s = "aaa bbb aaa bbb"
    >>> s[::-1].replace('bbb','xxx',1)[::-1]
    'aaa bbb aaa xxx'
    

    For your second example

    >>> s = "123123"
    >>> s[::-1].replace('2','x',1)[::-1]
    '1231x3'
    

提交回复
热议问题