Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right-to-left string replace in Python?

Tags:

python

string

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?

like image 516
fredley Avatar asked Mar 30 '12 13:03

fredley


People also ask

How do you replace part of a string in Python?

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.

What is .replace in Python?

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.

How do I replace a string in a list?

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 .


2 Answers

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

>>> 'XXX'.join('mississippi'.rsplit('iss', 1)) 'missXXXippi' 
like image 102
Stephen Emslie Avatar answered Sep 19 '22 08:09

Stephen Emslie


>>> myStr[::-1].replace("iss"[::-1], "XXX"[::-1], 1)[::-1] 'missXXXippi' 
like image 28
eumiro Avatar answered Sep 18 '22 08:09

eumiro