Python regex: how to replace each instance of an occurrence with a different value?
Suppose I have this string:
开发者_StackOverflows = "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")
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
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'
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
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)
精彩评论