预期的字符串或缓冲区(在re.sub中)

预期的字符串或缓冲区(在re.sub中),第1张

预期的字符串缓冲区(在re.sub中)

当您有多个匹配组时,

re.findall
返回
list
n-
tuple
s:

re.findall('(foo).(bar)', 'foo foo bar foo|bar')Out[5]: [('foo', 'bar'), ('foo', 'bar')]

因此,很明显每个

entry
in
tuples
是一个
tuple
。当您将传递
tuple
re.sub
时,它会抱怨。

tuples = re.findall('(foo).(bar)', 'foo foo bar foo|bar')for entry in tuples:    re.sub('oo','ox',entry).../usr/lib/python3.3/re.py in sub(pattern, repl, string, count, flags)    168     a callable, it's passed the match object and must return    169     a replacement string to be used."""--> 170     return _compile(pattern, flags).sub(repl, string, count)    171     172 def subn(pattern, repl, string, count=0, flags=0):TypeError: expected string or buffer

因此,做其他事情。也许使用

map

for entry in tuples:    print(' '.join(map(lambda s: re.sub('oo','ox',s),entry)))fox barfox bar

或者更容易理解

writer.writerow([re.sub(r'W', " ",s) for s in entry])

等等



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5661889.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存