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

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

    This is exactly what the rpartition function is used for:

    rpartition(...) S.rpartition(sep) -> (head, sep, tail)

    Search for the separator sep in S, starting at the end of S, and return
    the part before it, the separator itself, and the part after it.  If the
    separator is not found, return two empty strings and S.
    

    I wrote this function showing how to use rpartition in your use case:

    def replace_last(source_string, replace_what, replace_with):
        head, _sep, tail = source_string.rpartition(replace_what)
        return head + replace_with + tail
    
    s = "123123"
    r = replace_last(s, '2', 'x')
    print r
    

    Output:

    1231x3
    

提交回复
热议问题