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 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
216,810 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)