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

Y B
Y B
14,136 Points

Regex dictionary

I've spent an age on this and still can't get it. The individual parts in the below, pickup last name or first name and the age. and work with players.groupdict(). However combining them seems to great a list eg. with:

players = re.findall(r'(?P<last_name>[\w]+), (?P<first_name>[\w]+)', string, re.M) 

No idea why that doesn't work as a dictionary?

Also I'm not sure how to pick up multiple last names or first names.
eg. '(?P<last_name[\w]+ [\w]+?), ......

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]+), (?P<first_name>[\w]+): (?P<score>[\d]+)', string, re.M) 

5 Answers

Simon Leslie
Simon Leslie
23,690 Points

I can answer the second part of your query (about multiple last names / first names): you should include an explicit space in the set being search for like this:

(?P<last_name>[\w ]+)

There is space just after the '\w'.

Y B
Y B
14,136 Points

Thanks that helps, not sure why that works is [\w ]+ a set with 1 or more letter or spaces?

Now I have:

players = re.findall(r'(?P<last_name>[\w ]+), (?P<first_name>[\w ]+): (?P<score>[\d]+)', string, re.M) 

Which produces a list: [('Love', 'Kenneth', '20'), ('Chalkley', 'Andrew', '25'), ('McFarland', 'Dave', '10'), ('Kesten', 'Joy', '22'), ('Stewart Pinchback', 'Pinckney Benton', '18')]

not sure why?

Simon Leslie
Simon Leslie
23,690 Points

[\w ]+ will match a sequence of one or more characters (\w) or spaces.

As for the result being list, you are using .findall() instead of .search() or .match().

Y B
Y B
14,136 Points

Thanks that was it. I forgot to change it back after testing.

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

[\w\s] should work, too, for the names. You were, originally, just catching [\w] which won't match the spaces.