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

Chuang Poching
Chuang Poching
112 Points

word_length.py

I don't know how to write this task. Could anyone tell me why below code is incorrect? Thank you.

word_length.py
import re

# EXAMPLE:
# >>> find_words(4, "dog, cat, baby, balloon, me")
# ['baby', 'balloon']
def find_words(count, s):
    return re.findall(r'\w{,count}',s)

2 Answers

Steven Parker
Steven Parker
231,248 Points

You have the right general idea, but you don't want the word "count" as part of your regex string. Instead, use any method (like concatenation, format function, f-string, token substitution.) to put the value of the count into the string.

Also, to get "count or longer" you need to put the count value in front of the comma.

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points

You are on the right path. The string "count" in the current regex is literally the characters "count". For the argument count to be evaluated with in the string, it must be inserted into the string. Some methods:

# raw concatenation
r'\w{,' + str(count) + '}'
# f string uses double {{ to escape regular {
fr'\w{{,{count}}}' 
# format uses double {{ to escape regular {
r'\w{{,{}}}'.format(count),s) 
r'\w{{,{count}}}'.format(count=count),s)
# % s
r'\w{,%s}' % count