如何在python中处理AttributeError?

时间:2014-01-13 18:03:56

标签: python regex

我正在处理我在What's the most efficient way to find one of several substrings in Python?找到的一些示例代码。我已将代码更改为:

import re
to_find = re.compile("hello|there")
search_str = "blah fish cat dog haha"
match_obj = to_find.search(search_str)
#the_index = match_obj.start()  
which_word_matched = ""
which_word_matched = match_obj.group()  

由于现在没有匹配,我得到:

Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

python中处理不匹配场景的标准方法是什么,以避免错误

2 个答案:

答案 0 :(得分:4)

match_obj = to_find.search(search_str)
if match_obj:
    #do things with match_obj

如果您需要做某事,即使没有匹配,其他处理也会进入else区块。

答案 1 :(得分:3)

您的match_objNone,因为正则表达式不匹配。明确地测试它:

which_word_matched = match_obj.group() if match_obj else ''