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

Gilbert Craig
Gilbert Craig
2,102 Points

Classmethod contruction challenge - stumped

I am definitely stuck with this one ..... Any pointer greatly appreciated

    @classmethod
    def from_string(cls, string):
        answer = []
        for char in string:
            if char == 'dot':
                answer.append('.')
            elif char == 'dash':
                answer.append('_')
        return cls('-'.join(answer))

1 Answer

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 27,510 Points

You are very close! I can see you understood the concept pretty well.

I fixed the code and commented the lines where changes should take place.

Think of 'dot' and 'dash' as tokens in a string where tokens are separated by hyphens rather than thinking of the string in terms of a string iterable.

So... we create a LIST called tokens, which we split on the hyphens '-'... then your code will work. Also, the question wanted a LIST to be returned -- you built the list correctly as 'answer' -- so rather than joining it again to be a single string, just return the list.

Good luck with Python, it is worth the effort!

    @classmethod
    def from_string(cls, string):
        answer = []
        tokens = string.split('-')  # ADD THIS
        for char in tokens: # CHANGE ITERABLE to TOKENS LIST
            if char == 'dot':
                answer.append('.')
            elif char == 'dash':
                answer.append('_')
        return cls(answer) # RETURN THE LIST ANSWER RATHER THAN JOINING
Gilbert Craig
Gilbert Craig
2,102 Points

Thanks Jeff for the comprehensive answer