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

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

    I got a tricky answer, but it is not efficient enough

    
        >>> fname = '12345.png.pngasdfg.png'
        >>> suffix = '.png'
        >>> fname_rev = fname[::-1]
        >>> suffix_rev = suffix[::-1]
        >>> fullname_rev = fname_rev.replace(suffix_rev, '', 1)
        >>> fullname = fullname_rev[::-1]
        >>> fullname '12345.png.pngasdfg'
    
    

    Built-in function replace() takes three arguments str.replace(old, new, max_time) So you can delete the last mached string from the origional string

提交回复
热议问题