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

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