Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace two strings at once avoiding repeating replacement in Python?

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading