Right-to-left string replace in Python?

Solution 1:

rsplit and join could be used to simulate the effects of an rreplace

>>> 'XXX'.join('mississippi'.rsplit('iss', 1))
'missXXXippi'

Solution 2:

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

Solution 3:

>>> 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).