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

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

    When the wanted match is at the end of string, re.sub comes to the rescue.

    >>> import re
    >>> s = "aaa bbb aaa bbb"
    >>> s
    'aaa bbb aaa bbb'
    >>> re.sub('bbb$', 'xxx', s)
    'aaa bbb aaa xxx'
    >>> 
    
    0 讨论(0)
  • 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'
    
    0 讨论(0)
提交回复
热议问题