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


Camille Ferré
Camille Ferré
3,330 Points

Can't seem to print the class properly

Hi all,

During the python course, we need to create an address book, which I have done but I have a problem with my str method in the Person class. After the user enters what word he is looking for in the address book, the program should return all the Person in which this word was contained, so if someone is looking for '555' it should return all the persons that have 555 in their personal info but by showing all the info of the person (name, email,etc..). In my program below, it only shows one key and one value of the dictionary of the person. So if I look for "Tim" it will return for example "Twitter = None" when I would like it to return Tim, his email, phone number, etc.. What am I missing ?

import re

line = re.compile(r'''
                    ^(?P<name>[-\w ]*,\s[-\w ]+)\t
                    (?P<twitter>@ [\w\d]+)?$
                    ''', re.X|re.M)

class Person():
    def __init__(self, match):
        #turn match into dictionary 
        for key, value in match.groupdict().items():
            setattr(self, key, value)

    def __str__(self):
        for key, value in self.__dict__.items():
            return "{}: {}".format(key, value)


class Address():
    def __init__(self):
        self.names = open("names.txt", encoding="utf_8")
        self.data = self.names.read()
        self.contacts = [Person(match) for match in line.finditer(self.data)]

    def search(self):
        results = []

        search_term = input("What are you looking for? \n > ")

        for contact in self.contacts:
            for val in contact.__dict__.values():
                if val and re.search(search_term, val):
                    if contact not in results:

        if not results:
            print("Sorry, there was no results for your search")
            for result in results:


1 Answer

Chris Freeman
Chris Freeman
Treehouse Moderator 68,423 Points

Inside the __str__ method, the return is indented to be inside the for loop which makes it return in the first iteration.

Perhaps you want something like:

    def __str__(self):
        result = []
        for key, value in self.__dict__.items():
            result.append("{}: {}".format(key, value))
        return " ".join(result)

The trailing 'print("")' should be removed.