gpt4 book ai didi

python - 与 MatchObject.group() 相关的 re.sub() 错误

转载 作者:行者123 更新时间:2023-11-28 22:41:02 25 4
gpt4 key购买 nike

我有一个非常简单的 re.sub() 工作,但我无法让它正常工作。

import re
print re.sub(r"\d+", lambda x:x, "1 2 3 4 5")

匹配的字符串应该按原样打印,所以预期的输出是:

1 2 3 4 5

我得到的错误是:

Traceback (most recent call last):
File "_.py", line 2, in <module>
print re.sub(r"\d+", lambda x:x, "1 2 3 4 5")
File "/home/radar/anaconda/lib/python2.7/re.py", line 155, in sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: sequence item 0: expected string, _sre.SRE_Match found

最佳答案

替换函数传递了一个 match object通过 re.sub()。您直接返回该匹配对象,而您必须返回一个字符串;毕竟这就是将要用来替换(替换)原始匹配项的内容。

您可以通过 MatchObject.group() method 返回匹配的文本:

print re.sub(r"\d+", lambda x: x.group(), "1 2 3 4 5")

但是,您没有明确说明您预期会发生什么;上面将返回原始字符串,因为它用自己替换了每个数字:

>>> re.sub(r"\d+", lambda x: x.group(), "1 2 3 4 5")
'1 2 3 4 5'

或者您可以将数字递增 1(这需要转换为整数,然后在操作之后转换回字符串):

>>> re.sub(r"\d+", lambda x: str(int(x.group()) + 1), "1 2 3 4 5")
'2 3 4 5 6'

关于python - 与 MatchObject.group() 相关的 re.sub() 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33013138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com