Right-to-left string replace in Python?

后端 未结 7 736
轻奢々
轻奢々 2020-12-01 10:20

I want to do a string replace in Python, but only do the first instance going from right to left. In an ideal world I\'d have:

myStr = \"mississippi\"
print          


        
7条回答
  •  [愿得一人]
    2020-12-01 10:44

    you may reverse a string like so:

    myStr[::-1]
    

    to replace just add the .replace:

    print myStr[::-1].replace("iss","XXX",1)
    

    however now your string is backwards, so re-reverse it:

    myStr[::-1].replace("iss","XXX",1)[::-1]
    

    and you're done. If your replace strings are static just reverse them in file to reduce overhead. If not, the same trick will work.

    myStr[::-1].replace("iss"[::-1],"XXX"[::-1],1)[::-1]
    

提交回复
热议问题