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

George Clement
George Clement
2,816 Points

Magic method

I am not sure what to do with this one... I know the replaces I am using are ugly but not sure why they are failing

morse.py
class Letter:
    def __init__(self, pattern=None):
        self.pattern = pattern

    def __string__(self):

    def __str__(self):
        string_copy1 = self.pattern
        string_copy2 = string_copy1.replace(".", "dot")
        string_copy3 = string_copy2.replace("_", "dash")
        string_copy4 = string_copy3.replace(" ", "-")

        return string_copy4


class S(Letter):
    def __init__(self):
        pattern = ['.', '.', '.']
        super().__init__(pattern)

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 67,986 Points

Though your solution is not as efficient as a single pass for loop, it would work with the following corrections:

  • self.pattern is a list, so it should be converted to a string before using executing the replacements:
string_copy1 = " ".join(self.pattern)
  • The extraneous method __string__ is incomplete. Remove or add a pass statement

You can further simplify your solution by

  • using "-".join() so the space-to-hyphen is already done.
  • no need to create a new string "copy", you may reassign the result to string which overwrites the previous value

Post back if you need more help. Good luck!