Right-to-left string replace in Python?

后端 未结 7 756
轻奢々
轻奢々 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:50

    >>> re.sub(r'(.*)iss',r'\1XXX',myStr)
    'missXXXippi'
    

    The regex engine cosumes all the string and then starts backtracking untill iss is found. Then it replaces the found string with the needed pattern.


    Some speed tests

    The solution with [::-1] turns out to be faster.

    The solution with re was only faster for long strings (longer than 1 million symbols).

提交回复
热议问题