I am trying to replace two strings using python in a text like:
text="This is a rhopialg, not a rhopi"
I want to exactly replace "rhopialg" by "myrhopialg", replace "rhopi" by "myrhopi"
If I use text.replace('rhopialg' , 'myrhopialg').replace('rhopi','myrhopi'), the result is
"This is a mymyrhopialg, not a myrhopi.", The first word replaced two times, not correct.
The expected result after replace is: "This is a myrhopialg, not a myrhopi"
How to achieve this ensuring replace only once?
>Solution :
Use a regex:
import re
text = "This is a rhopialg, not a rhopi"
out = re.sub('rhopialg|rhopi' , 'myrhopi', text)
Or, to restrict to full words:
out = re.sub(r'\b(rhopialg|rhopi)\b' , 'myrhopi', text)
To compress the regex, since part of the string is common:
out = re.sub(r'\brhopi(?:alg)?\b' , 'myrhopi', text)
Output: 'This is a myrhopi, not a myrhopi'