python 使用正则表达式多次替换相同模式

6ss1mwsb  于 2023-01-04  发布在  Python
关注(0)|答案(2)|浏览(141)

这段代码使用正则表达式和python在字符串中进行替换。2使用count标记你也可以说要替换多少个示例。

first = "33,33"
second = '22,55'
re.sub(r"\d+\,\d+", first, "There are 2,30 foo and 4,56 faa", count=1)
output: 'There are 33,33 foo and 4,56 faa'

但是,我如何对同一个模式进行多个(不同的值)替换呢?我想这样做:

re.sub(r"\d+\,\d+", [first,second], "There are 2,30 foo and 4,56 faa", count=2)
desired output: 'There are 33,33 foo and 22,55 faa'
p4rjhz4m

p4rjhz4m1#

我们可以通过回调函数使用re.sub

inp = "There are 2,30 foo and 4,56 faa"
repl = ["33,33", "22,55"]
output = re.sub(r'\d+,\d+', lambda m: repl.pop(0), inp)
print(output)  # There are 33,33 foo and 22,55 faa
4jb9z9bj

4jb9z9bj2#

您可以使用iter执行以下任务:

import re

first = "33,33"
second = "22,55"

i = iter([first, second])

out = re.sub(r"\d+\,\d+", lambda _: next(i), "There are 2,30 foo and 4,56 faa")
print(out)

图纸:

There are 33,33 foo and 22,55 faa

相关问题