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

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

    Here is a solution based on a simplistic interpretation of your question. A better answer will require more information.

    >>> s = "aaa bbb aaa bbb"
    >>> separator = " "
    >>> parts = s.split(separator)
    >>> separator.join(parts[:-1] + ["xxx"])
    'aaa bbb aaa xxx'
    

    Update

    (After seeing edited question) another very specific answer.

    >>> s = "123123"
    >>> separator = "2"
    >>> parts = s.split(separator)
    >>> separator.join(parts[:-1]) + "x" + parts[-1]
    '1231x3'
    

    Update 2

    There is far better way to do this. Courtesy @mizipzor.

提交回复
热议问题