从re.sub调用函数

2024-04-19 10:01:05 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个简单的例子:

import re

math='<m>3+5</m>'
print re.sub(r'<(.)>(\d+?)\+(\d+?)</\1>', int(r'\2') + int(r'\3'), math)

它给了我这个错误:

ValueError: invalid literal for int() with base 10: '\\2'

它发送\\2,而不是35

为什么? 我该怎么解决?


Tags: importreforbase错误withmath例子
2条回答

如果要将函数与re.sub一起使用,则需要传递函数而不是表达式。如here所述,函数应将match对象作为参数并返回替换字符串。您可以使用常用的.group(n)方法等访问组。例如:

re.sub("(a+)(b+)", lambda match: "{0} as and {1} bs ".format(
    len(match.group(1)), len(match.group(2))
), "aaabbaabbbaaaabb")
# Output is '3 as and 2 bs 2 as and 3 bs 4 as and 2 bs '

注意,函数应该返回字符串(因为它们将被放回原始字符串中)。

您需要使用lambda函数。

print re.sub(r'<(.)>(\d+?)\+(\d+?)</\1>', lambda m: str(int(m.group(2)) + int(m.group(3))), math)

相关问题 更多 >