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

Andrei Oprescu
Andrei Oprescu
9,547 Points

i need some help with completing this code challenge

Hello! I have come across a challenge that asks me this question:

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.

the code that I used for this question is down at the bottom of the challenge.

I know what I have done wrong, but can someone explain to me how I can put 'count' number of times how many letters there have to be?

Thanks!

Andrei

word_length.py
import re

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

3 Answers

Steven Parker
Steven Parker
221,070 Points

You've got the right idea, but you don't want the word "count" in your regex. To get the value represented by the variable "count" instead, you could use concatenation to put the string version of the value into the regex:

    return re.findall(r'\w{' + str(count) + ',}', string)

Another way would be to use a formatted string to insert the value using interpolation:

    return re.findall(f'\w{{{count},}}', string)
Andrei Oprescu
Andrei Oprescu
9,547 Points

Hi!

Thank you for helping me, but I have a question, why is count concatenated as the string format and not the integer format?

Andrei

Steven Parker
Steven Parker
221,070 Points

Concatenation is only done with strings, so the number must be converted into a string. Formatting, either by interpolation or using "format", handles the conversion for you.

Andrei Oprescu
Andrei Oprescu
9,547 Points

Hi! Thank you for explaining the reason behind this.

Andrei