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

Y B
Y B
14,136 Points

findall challenge doesn't quite work

Using the code below fails the test, however if I replace count by 4 in the example then the code seems to work fine. I'm not clear why using the variable count in place of the 4 stops it being recognised and produces the empty list?

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

Using count inside of the string prevents Python from detecting it as a variable. Try multiplying the escape character string by count and then adding it to zero or more escape characters. Your answer should have two different strings.

Y B
Y B
14,136 Points

That makes sense but I couldn't get that to work either...

def find_words(count, string):
  return re.findall(r'\w'*count, string)

ps what is the escape character?

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

The escape character is \. You want count+ occurrences, though, so you need to get the count into the string. If only there was some way to concatenate strings together... :D

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

How is the count variable getting into your pattern?

Y B
Y B
14,136 Points

I did question that at one point I tried using the format method as per the earlier course on string so I tried

def find_words(count, string):
    return re.findall(r'\w{}'.format(count), string)

but that just gave me the empty list? Format doesn't feel like the right method here, although perhaps it's effectively putting the int count into the {} to get e.g. '\w{4}' which worked for the example. So I'm not sure why this doesn't work?

Y B
Y B
14,136 Points

4+ or count+, I hadn't grasped that I needed the + at all. Thanks for your very patient help.