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

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
230,274 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
230,274 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