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

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 28,716 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