Python 如何在函数中使用re.search?
我在ubuntu命令行中使用python,下面是我的代码:Python 如何在函数中使用re.search?,python,Python,我在ubuntu命令行中使用python,下面是我的代码: import re from sys import stdin def find(pat,text): m= re.match(pat,text) if m: print m.groups() else: print m.groups() pat=stdin.readline() text=stdin.readline() answer= find(pat,text) 就这
import re
from sys import stdin
def find(pat,text):
m= re.match(pat,text)
if m:
print m.groups()
else:
print m.groups()
pat=stdin.readline()
text=stdin.readline()
answer= find(pat,text)
就这些。。。我得到的错误是:
AttributeError: 'NoneType' object has no attribute 'groups'
我认为这是因为你的else语句,如果re.match失败,他会给你一个None-objects 你可以用
m.groups()
只要你匹配
比如说
str1 = "toto is happy"
print re.match("toto",str1).group()
将输出
“托托”
但是
当您已经知道
m
的值为None
时,将失败并在else
块中显示您的错误,为什么要执行m.groups()
?是的,当im使用命令行时,senario不会失败。。我的输入是find(a,abc),所以它应该匹配
str1 = "toto is happy"
print re.match("test",str1).group()