Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Regular Expressions in Python Introduction to Regular Expressions Groups

Alfonso Quijano
Alfonso Quijano
14,834 Points

why when we use findall intead search we find this Error object has no attribute 'groupdict'

python, Groups

2 Answers

Mischa Yartsev
Mischa Yartsev
20,548 Points

Hi, Alfonso Quijano

This is because .findall method is returning a 'list' object and therefore doesn't have a .groupdict method

findall = re.findall(r'(?P<twitter>@[\w\d]+)$', string, re.I|re.M)
# ['@kennethlove', '@chalkers', '@davemcfarland', '@joykesten']
# <class 'list'>

On the other hand, .search method returns 're.Match' object that has the 'groupdict' method included

search = re.search(r'(?P<twitter>@[\w\d]+)$', string, re.I|re.M)
# <re.Match object; span=(66, 78), match='@kennethlove'>
<class 're.Match'>

Don't forget that you could always use dir() function to check what kind of attributes or methods your variables got inside

# ['__class__', '__copy__', '__deepcopy__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'end', 'endpos', 'expand', 'group', 'groupdict', 'groups', 'lastgroup', 'lastindex', 'pos', 're', 'regs', 'span', 'start', 'string']
Kerrick Hahn
Kerrick Hahn
5,728 Points

I had same problem.

For me, I had to take out the 'print' statement from the variable assignment for, 'line ='