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

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

    Using regular expression function re.sub to replace words at end of string

    import re
    s = "123123"
    s = re.sub('23$', 'penguins', s)
    print s
    

    Prints:

    1231penguins
    

    or

    import re
    s = "123123"
    s = re.sub('^12', 'penguins', s)
    print s
    

    Prints:

    penguins3123
    

提交回复
热议问题