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

python-regex : change the desired word

I use the search functionre.finditer() and get span as 1 tuple
Example: text = "Thanks for the help, your Help is really good, it’s really a big help"
I’ve used

import re
text = "Thanks for the help, your Help is really good, it's really a big help"
for key in re.finditer('help',text,re.I):
   print(key.group())
   cvt = text.replace('help','job')
   print(cvt)

to change from ‘2nd help’ to ‘job’ but it converts all words. How to make it only switch words that i want

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

>Solution :

Using re.sub would be easier than re.finditer:

import re
text = "Thanks for the help, your Help is really good, it's really a big help"
text = re.sub('help', 'job', text, flags=re.I)
print(text)
# => Thanks for the job, your job is really good, it's really a big job

If you really need to use re.finditer, then you need to cut-and-paste the string yourself. You also want to reverse the matches, because the indices for later matches will get messed up with earlier edits ("cutting the branch you are sitting on").

import re
text = "Thanks for the help, your Help is really good, it's really a big help"
for match in reversed(list(re.finditer('help', text, re.I))):
    text = text[:match.start(0)] + "job" + text[match.end(0):]
print(text)
# => Thanks for the job, your job is really good, it's really a big job

To only switch the items you want, you either make a more precise regex, or find a different criterion to do so. For example, to only replace the second one, which is capitalised, you could search for "Help" instead of "help", and not specify the re.I flag. Or you could search for (?<=help.*)help with re.I (a "help" that is preceded by another "help"). Or you could use re.sub with a replacer function and a nonlocal counter, so that you only replace the second match. Or you could use re.finditer to find a list of matches, extract the second one, and then perform the cut-and-paste from the first example.

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