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 Sets

Peter Brandstetter
Peter Brandstetter
7,163 Points

Using variables for min. or max. length of a match


In the task before we were asked to write a code, to find words with min. x letters, where x gets passed as argument to a function. I tried to use the variable like this:

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

What would be the correct way to be able to use the variable?


1 Answer

Steven Parker
Steven Parker
228,978 Points

You were getting close, but:

  • you might want to use a different parameter name so you don't shadow the "str" function
  • you could use that function to convert the count into a string and concatenate with the rest of the regex
  • don't put a space after the comma in the regex
def find_words(count, string):
    return re.findall(r'\w{' + str(count) + ',}', string)