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 Word Length

Error: "Didnยดt get the right output. Output was ['123456', Treehouse', student', 'Kenneth', 'Python']. Length was 6."

In this exercise my idea was to find everything that is not a space. Later I created a new list with the words to do a filter after that with if statement.

Any clue of what I'm doing wrong would be apreciated Thanks!!!

word_length.py
import re

# EXAMPLE:
# >>> find_words(4, "dog, cat, baby, balloon, me")
# ['baby', 'balloon']


def find_words(n, s):
    a = re.findall(r'\S', s)
    s = ""
    t = []
    t1 = []
    for i in a:
        if i != ',':
            s += i
        else:
            t.append(s)
            s = ""
    for i in t:
        if len(i) >= n:
            t1.append(i)
    return t1







    return t1

1 Answer

Julian Garcia
Julian Garcia
18,380 Points

"dog, cat, baby, balloon, me"

I could describe with regex the string as follows:

there is a word: \w+
there is a comma: ,   
could exist or not a comma: ,?
there is a space:\s
could exist or not a space: \s?

If you look at string you could check that the string is represented by:

there is a word and could exist or not a comma and could exist or not  a space

this in terms of regular expressions is:

'(\w+),?\s?'     two parenthesis means a group what findall
                 is going to return, in this case the word only without comma
                 and space.

that regular expression with findall returns :

['dog', 'cat', 'baby', 'balloon', 'me']

From there you just need to filter with if-else statements to determine
which of them are greater than count and return then in a list