12

Suppose I have this string: s = "blah blah blah"

Using Python regex, how can I replace each instance of "blah" with a different value (e.g. I have a list of values v = ("1", "2", "3")

4 Answers 4

24

You could use a re.sub callback:

import re
def callback(match):
    return next(callback.v)
callback.v=iter(('1','2','3'))

s = "blah blah blah"
print(re.sub(r'blah',callback,s))

yields

1 2 3
Sign up to request clarification or add additional context in comments.

3 Comments

Adding the iterable to the function as an attribute is a really nice approach.
This is a beautiful solution.
a closure would be way saner.
14

You could use re.sub, which takes a string or function and applies it to each match:

>>> re.sub('blah', lambda m, i=iter('123'): next(i), 'blah blah blah')
<<< '1 2 3'

Comments

2

In this case, you don't need regex:

s.replace("blah","%s")%v

the replace produces "%s %s %s", then you use the format operator

1 Comment

As long as s does not contain %.
2

I think you don't really need a regex.

for x in v:
  s = s.replace('blah', x, 1)

However if you really wanted a regex:

import re
for x in v:
  s = re.sub('blah', x, s, count=1)

1 Comment

I see two problems with this: 1) It's inefficient, because each call to .replace starts searching for an occurence to replace at the start of the string. 2) It straight up doesn't work if v contains the word "blah".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.