0

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

2 Answers 2

4
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.

Sign up to request clarification or add additional context in comments.

Comments

3

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 ''

2 Comments

Much appreciated - Bill
This is an interesting way to phrase it. I haven't seen this before.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.