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 trialAlex Rodriguez
Front End Web Development Techdegree Student 20,810 PointsCan't figure out whats wrong with names.py challenge
Instructions: Create a variable names that is an re.match() against string. The pattern should provide two groups, one for a last name match and one for a first name match. The name parts are separated by a comma and a space.
Error: Didn't get the right content in the groups. Last name was "Perotto,", first name was " Pier Giorgio".
My Code:
import re
string = 'Perotto, Pier Giorgio'
names = re.match(r''' (?P<last>[\w]+,) (?P<first>[\s\w]+) ''', string, re.X)
I am no sure what I am doing wrong here, I tried this in workspace and it returned the right answer.
import re
string = 'Perotto, Pier Giorgio'
names = re.match(r'''
(?P<last>[\w]+,)
(?P<first>[\s\w]+)
''', string, re.X)
2 Answers
Chris Freeman
Treehouse Moderator 68,457 PointsYou are very close. The separating comma should be outside the group, and you needed to catch the SPACE between the names:
names = re.match(r'''
(?P<last>[\w]+),\s # <-- moved comma and added "\s"
(?P<first>[\s\w]+)
''', string, re.X)
Sahar Nasiri
7,454 PointsThank you for your answer, But I meant the \s in (?P<first>[\s\w]+). You wrote a \s after "," and then you wrote another one (?P<first>[\s\w]+).
[MOD: fixed format by adding <
instead of < and >
instead of > -cf]
Chris Freeman
Treehouse Moderator 68,457 PointsThe \s
in the pattern for "first" was in your original post. I merely copied it. The \s
could be replaced by a typed space " ".
I should correct my use of \s
. It matches WHITESPACE including space, tab, newline, carriage return, form feed, vertical tab. if you explicitly want a SPACE use the typed " " or enclose it in brackets: [ ]
Sahar Nasiri
7,454 PointsSahar Nasiri
7,454 PointsWhy do you add the second \s? What's the difference between these \s es?
Chris Freeman
Treehouse Moderator 68,457 PointsChris Freeman
Treehouse Moderator 68,457 PointsThe
re.X
(verbose) flag allows you to write the pattern over several lines but it also then ignores regular spaces. The\s
is a placeholder for the SPACE that follows the comma. In other Treehouse challenges, the data is separated by TABs so the\t
placeholder will be needed.