【问题标题】:How to handle AttributeError in python?如何在python中处理AttributeError?
【发布时间】:2014-02-01 14:36:16
【问题描述】:

我正在研究我在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中处理不匹配场景的标准方法是什么,以避免错误

【问题讨论】:

    标签: python regex


    【解决方案1】:
    match_obj = to_find.search(search_str)
    if match_obj:
        #do things with match_obj
    

    如果您需要做某事,即使没有匹配项,其他处理也将放在 else 块中。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 非常感谢 - 比尔
      • 这是一种有趣的表达方式。我以前没见过这个。
      猜你喜欢
      • 1970-01-01
      • 2014-11-16
      • 2019-02-14
      • 1970-01-01
      • 1970-01-01
      • 2011-05-09
      • 2020-07-18
      • 1970-01-01
      • 2013-01-04
      相关资源
      最近更新 更多