开发者

Python regex: how to replace each instance of an occurrence with a different value?

开发者 https://www.devze.com 2023-04-02 09:25 出处:网络
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\",

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消