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 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
221,070 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,154 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