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 myStr.rreplace("iss","XXX",1) > missXXXippi
What's the best way of doing this, given that rreplace
doesn't exist?
Python String | replace() replace() is an inbuilt function in the Python programming language that returns a copy of the string where all occurrences of a substring are replaced with another substring. Parameters : old – old substring you want to replace. new – new substring which would replace the old substring.
The replace() method is a built-in functionality offered in Python programming. It replaces all the occurrences of the old substring with the new substring. Replace() returns a new string in which old substring is replaced with the new substring.
Replace a specific string in a list. If you want to replace the string of elements of a list, use the string method replace() for each element with the list comprehension. If there is no string to be replaced, applying replace() will not change it, so you don't need to select an element with if condition .
rsplit
and join
could be used to simulate the effects of an rreplace
>>> 'XXX'.join('mississippi'.rsplit('iss', 1)) 'missXXXippi'
>>> myStr[::-1].replace("iss"[::-1], "XXX"[::-1], 1)[::-1] 'missXXXippi'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With