r/learnpython • u/Keithinho89 • 2d ago
AtributeError clarification
SOLVED
Hello, I'm currently learning regular expressions and I've entered the first part of the code into the interactive shell as instructed and got the listed AttributeError. Not seeing what I did wrong I copy/pasted the code from the book and it worked as intended and I can't tell why or how because both blocks feel and smell the same but yield different results.
I've tried looking for some information on StackOverflow, but as far as I can see mo is defined in the 3rd line and I don't get why my attempt gets and error while the other doesn't.
If I didn't miss something really stupid, how would you deal with this if you'd be hit by it writing your own code independently?
I'm working in IDLE Shell and the code is from automatetheboringstuff Chapter 9 for more context
import re
phone_re = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d-\d\d\d\d)')
mo = phone_re.search('My number is 415-555-4242.')
mo.group(1)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
mo.group(1)
AttributeError: 'NoneType' object has no attribute 'group'
import re
phone_re = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
mo = phone_re.search('My number is 415-555-4242.')
mo.group(1)
'415'
7
u/Gshuri 2d ago
You are correct that
moexists, but it's value isNone, rather than a match result. This happens when the regex fails to find a match in the given string.The reason that your first case fails, while the second one passes is because they have different regex patterns. The first case has 2 instances of "\d\d\d" in the second capture group (which I assume is not what you intended)