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

Using a variable in an expression quantifier ?

When I try to use "count" as my quantifier here I always get an empty list back

If I run this in my own terminal but have count explicitly defined (e.g. as 4) then I do get expected results... for example:

find_words(4, "dog, cat, baby, balloon, me") ['baby', 'balloon']

(although 4 is still passed I do not use it, I have the number 4 explicitly in the same code line as the snippet here but in the place of "count"

word_length.py
import re

# EXAMPLE:
# >>> find_words(4, "dog, cat, baby, balloon, me")
# ['baby', 'balloon']

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

1 Answer

Dan Johnson
Dan Johnson
40,533 Points

You'll need to use something like format or convert count into a string and then concatenate the regular expression in order to get at its value.

Here's an example with concatenation:

regex = "\\w{" + str(count) + ",}"