user1592380
user1592380

Reputation: 36307

How to handle AttributeError in python?

I am working through some example code which I've found on What's the most efficient way to find one of several substrings in Python?. I've changed the code to:

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()  

Since there is now no match , I get:

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

What is the standard way in python to handle the scenario of no match, so as to avoid the error

Upvotes: 0

Views: 701

Answers (2)

roippi
roippi

Reputation: 25974

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

Other handling will go in an else block if you need to do something even when there's no match.

Upvotes: 4

Martijn Pieters
Martijn Pieters

Reputation: 1123410

Your match_obj is None because the regular expression did not match. Test for it explicitly:

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

Upvotes: 3

Related Questions