通过使用列表指定要插入的值,是否可以基于相同的匹配模式在字符串中插入不同的值?我正在使用python 3和re.附属的.
以下是a的意思:
line = "Float: __, string: __"
values = ["float", "string"]
newLine = re.sub('(_+)([.]_+)?',
(lambda m:
f'%'
f'{len(m.group(1))}'
f'{"." if values == "float" else ""}'
f'{(len(m.group(2) or ".")-1) if values == "float" else ""}'
f'{"f" if values == "float" else "s"}'),
line)
print(newLine)
预期结果:
Float: %2.0f, string: %2s
实际结果:
Float: %2s, string: %2s
是否可以循环遍历值列表以获得正确的结果(这不起作用,我得到了一个TypeError)?类似于:
newLine = re.sub('(_+)([.]_+)?',
((lambda m:
f'%'
f'{len(m.group(1))}'
f'{"." if v == "float" else ""}'
f'{(len(m.group(2) or ".")-1) if v == "float" else ""}'
f'{"f" if v == "float" else "s"}') for v in values),
line)
Edit 1