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 Name Groups

Leo Marco Corpuz
Leo Marco Corpuz
18,975 Points

Python name groups

My code is not complete but I need feedback on whatโ€™s missing or what needs to be corrected.

names.py
import re

string = 'Perotto, Pier Giorgio'
names=re.match("?P<last name>(P\w+)\W\s?P<first name>(P\w+)",string)
print(names.groups())
Leo Marco Corpuz
Leo Marco Corpuz
18,975 Points

Here's my updated code. I don't understand the third correction. Isn't "\s" used for a space?

import re

string = 'Perotto, Pier Giorgio'
names=re.match(r'(?P<last_name>(P\w+)\W\s<first_name>(P\w+)'),string)
print(names.groups())

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points

You are very close. Here are the items to correct:

  • The named groups should be of the form (?P<group_name>regex). As you have it, the opening paren is in the wrong place and there is an extra "P" in the pattern.
  • The group names can not have a space. This should be an underscore _
  • The first_name group should accept a space in the name. Hint: you can use a character set: [ \w]
  • To avoid using double backslashes \\, the string should be prefixed with an r to signify a "raw string" where the single backslash isn't interpreted as an escape. Otherwise, all single-backslashes would have to be coded as double-backslashes.

With these corrections, the code should pass.

Post back if you need more help. Good luck!!

Chris Freeman
Chris Freeman
Treehouse Moderator 68,441 Points

Leo Marco Corpuz, youโ€™re getting closer! In your updated code:

names=re.match(r'(?P<last_name>(P\w+)\W\s<first_name>(P\w+)'),string)

Bullet points 2 & 4 were fixed, but not the point 1 & 3.

The \s you have between the groups is correct. There needs to be something additional in the pattern for the first_name group to account for the space between the two first names. See the section on [] Used to indicate a set of characters in the re docs.

Leo Marco Corpuz
Leo Marco Corpuz
18,975 Points

Thanks for your help! It turns out I didn't need to use '?P<>' in this challenge. I forgot to include the 'Giorgio' pattern of the first name.