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 Players Dictionary and Class

January Johnson
January Johnson
23,798 Points

Didn't get the expected match

When I run my code in VSCode I get <re.Match object; span=(0, 17), match='Love, Kenneth: 20'>

But Treehouse keeps giving me

Bummer: Didn't get the expected match. Got "{'last_name': 'Love', 'first_name': ' Kenneth', 'score': ' 20'}".

players.py
import re

string = '''Love, Kenneth: 20
Chalkley, Andrew: 25
McFarland, Dave: 10
Kesten, Joy: 22
Stewart Pinchback, Pinckney Benton: 18'''

players = re.search(r'''
(?P<last_name>[\w]+\s?[\w]+?), #last name
(?P<first_name>\s[-\w]*?\s?[\w]*): #first_name
(?P<score>\s[\d]+) #score
''', string, re.X|re.M)

2 Answers

Steven Parker
Steven Parker
210,487 Points

The regex should account for spaces between the elements, but not include leading spaces as part of the elements.

Got "{'last_name': 'Love', 'first_name': ' Kenneth', 'score': ' 20'}
                                          ^                    ^
                                          |-- leading spaces --|
January Johnson
January Johnson
23,798 Points

Figured it out. I just needed to change where I was putting \s. Still, I wonder why I couldn't get the lookaround sequence to work. ??

Steven Parker
Steven Parker
210,487 Points

The lookbehind would match a name that folllows a space, but it doesn't account for having a space between the comma and the name. You still need a space (or space character class) in between the named ranges.

January Johnson
January Johnson
23,798 Points

I see. Unfortunately, the only way I understand to match but not capture the \s is to use a lookaround expression (?<=\s). But it doesn't work.