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

Mo Reese
Mo Reese
11,868 Points

Regular Expressions in Python - Word Length Challenge Only returns an Empty List

I am not understanding why my code yields an empty list; since \w{n, } should match n or more word characters in a row, correct? Can anyone please help me understand what I am missing?

Instructions for challenge: Create a function named find_words that takes a count and a string. Return a list of all of the words in the string that are count word characters long or longer.

word_length.py
import re


def find_words(c, s):
    return re.findall(r'\w{c,}', s)

1 Answer

Steven Parker
Steven Parker
230,946 Points

Remember that characters in a string literal only represent themselves. To include the value of the parameter in the string, try using concatenation or a formatting function.

Mo Reese
Mo Reese
11,868 Points

ok, so I'm trying to apply your words to my "solution" above and compare it to the solution below-which passes the challenge... I'm still not understanding why my solution is no good, but the other is. I see the subtle difference in code (concatenation), but I don't get why that is necessary. I feel like they are both saying the same thing. Are you able to shed some light? Thanks in advance...

def find_words(c, s):
    return re.findall(r'\w' * c + '\w*', s)
Steven Parker
Steven Parker
230,946 Points

That example uses a completely different syntax for the regex. One that would work with braces syntax might look like this:

    return re.findall(r'\w{' + str(c) + ',}', s)

So where the original had the actual letter "c" inside the braces, this one would put the numeric value c represents there (after converting it to a string).