例如,我有一个像这样的字符串:
'blah blah 1.344 blah 1.455'
和一个像这样的列表:
[2.888, 4.033]
我知道字符串和列表包含相同数量的数字,并且想使用正则表达式将字符串中的所有数字替换为列表中的数字。我想要这样的东西:
re.sub('\d\.\d+', list[i], line)
但不知道如何让它用列表中的下一个项目替换每个匹配项,而不仅仅是相同的项目。我想保留所有文本和所有空白完全相同,所以拆分成一个列表,用索引替换并重新加入似乎不是我需要的。
最佳答案
re.sub
的第二个repl
参数可以是任意函数,它接受单个 match
对象并返回一个字符串来替换它。在你的情况下:
>>> import re
>>> repl = [2.888, 4.033]
>>> re.sub(
r'\d\.\d+', # note raw string to avoid issues with backslashes
lambda match: str(repl.pop(0)), # replace each match with the next item in the list
'blah blah 1.344 blah 1.455'
)
'blah blah 2.888 blah 4.033'
关于python - 按顺序用列表中的项目替换字符串中的正则表达式匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31005138/