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

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

    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'
    

提交回复
热议问题