Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Regular Expressions in Python Introduction to Regular Expressions Groups

Alfonso Quijano
Alfonso Quijano
15,137 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,562 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']
type(findall)
# <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'>
type(search)
<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

dir(search)
# ['__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 ='