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

Not able to get the task 2 from the last challenge in Regular Expression Course:

Question: Wow! OK, now, create a class named Player that has those same three attributes, last_name, first_name, and score. I should be able to set them through init.

I am new to python. Can you please explain me how to solve this question.

players.py
import re

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

regex = re.compile(r'^(?P<last_name>[a-zA-Z\s]+),\s(?P<first_name>[a-zA-Z\s]+):\s(?P<score>[0-9]+)$', re.MULTILINE)
players = re.search(regex, string)

class Player:
    last_name = ""
    first_name = ""
    score = 0

Hi Chris, Thanks for reaching to help. Sorry I've updated the code now.

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

The next step is to add an __init__ method. It should take self and keyword arguments last_name, first_name, and score. Use these kwargs to set the local attributes.

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

I get an error : Wasn't able to create correct instances. Got {}.

players.py
import re

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


regex = re.compile(r'^(?P<last_name>[a-zA-Z\s]+),\s(?P<first_name>[a-zA-Z\s]+):\s(?P<score>[0-9]+)$', re.MULTILINE)
players = re.search(regex, string)

class Player:
    last_name = ""
    first_name = ""
    score = 0
    def __init__(self,**kwargs):
        last_name,first_name,score =kwargs
Chris Freeman
Chris Freeman
Treehouse Moderator 68,423 Points

It's better, in this case, to explicitly list each keyword argument in the __init__. Also the assignments need to be to attributes in the form self.last_name = last_name

Thanks a lot Chris!