Replacing each match with another word

I have a regex:

findthe = re.compile(r" the ") replacement = ["firstthe", "secondthe"] sentence = "This is the first sentence in the whole universe!" 

What I'm trying to do is replace each occurrence with a related replacement word from the list so that the final sentence looks like this:

 >>> print sentence This is firstthe first sentence in secondthe whole universe 

I tried using re.sub inside the for loop listing the replacement, but it looks like re.sub returns all occurrences. Can someone tell me how to do this efficiently?

+7
source share
3 answers

If you do not need to use regEx, you can try using the following code:

 replacement = ["firstthe", "secondthe"] sentence = "This is the first sentence in the whole universe!" words = sentence.split() counter = 0 for i,word in enumerate(words): if word == 'the': words[i] = replacement[counter] counter += 1 sentence = ' '.join(words) 

Or something like this will work too:

 import re findthe = re.compile(r"\b(the)\b") print re.sub(findthe, replacement[1],re.sub(findthe, replacement[0],sentence, 1), 1) 

And at least:

 re.sub(findthe, lambda matchObj: replacement.pop(0),sentence) 
+6
source

Arcium's final answer destroys the replacement variable. Here you can do it without emptying replacement

 re.sub(findthe, lambda m, r=iter(replacement): next(r), sentence) 
+4
source

You can use the callback function as a replace parameter, see how:

http://docs.python.org/library/re.html#re.sub

Then use some counter and replace it depending on the value of the counter.

+2
source

All Articles