2024-04-19 10:01:05 发布
网友
这是一个简单的例子:
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,而不是3和5。
\\2
3
5
为什么? 我该怎么解决?
如果要将函数与re.sub一起使用,则需要传递函数而不是表达式。如here所述,函数应将match对象作为参数并返回替换字符串。您可以使用常用的.group(n)方法等访问组。例如:
re.sub
.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)
如果要将函数与
re.sub
一起使用,则需要传递函数而不是表达式。如here所述,函数应将match对象作为参数并返回替换字符串。您可以使用常用的.group(n)
方法等访问组。例如:注意,函数应该返回字符串(因为它们将被放回原始字符串中)。
您需要使用lambda函数。
相关问题 更多 >
编程相关推荐