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

STAGE 1 REGULAR EXPRESSION

Create a variable named players that is an re.search() or re.match() to capture three groups: last_name, first_name, and score. It should include re.MULTILINE

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(?Pfirst_name>\w+):\s(?P<score>\dt',string,re.M)

4 Answers

KAZUYA NAKAJIMA
KAZUYA NAKAJIMA
8,851 Points

Now I solved it with above help.

  • [] for group of character
  • use re.X and use.M
  • "Stewart Pinchback", "Pinckney Benton" contains space in both first and last name
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
  (?P<first_name>[\w ]*)
  :\s
  (?P<score>[\d]*)
''', string, re.X | re.M)
Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Some of the last names and first names aren't single words. Your pattern is only looking for single characters for names, even.

TypeError: expected string or buffer..... does this mean I have to use str? ....

players = re.search(r'''
  (?P<name>[-\w ]+,\s[-\w ]+)\t   #  last and first names
  (?P<score>\(?\d{2}\)?)     # score
''', re.MULTILINE)

print(players)
Kenneth Love
Kenneth Love
Treehouse Guest Teacher

There aren't any tabs (\t) for you to catch.

And you didn't give a string to match the pattern against to the search() function.

re.search([pattern], [string], [flags])

import re

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

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

I think you need to include the separating characters (commas, spaces, colons) outside of your named groups