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

Pete P
Pete P
7,613 Points

Inserting a variable into a regex?

This one had me stumped for about 10 min:

'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.'

This code is what I came up with. I'm interested in knowing if there is a different solution to this challenge.

Thanks Again!

-Pete

word_length.py
import re

# EXAMPLE:
# >>> find_words(4, "dog, cat, baby, balloon, me")
# ['baby', 'balloon']
def find_words(count, sarg):
  return re.findall(r'\w{%i,}' % count, sarg)

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

Your code is spot on (I like the use of regex ranges). The regex is looking for a string. and any process of constructing with the correct "count" in the string also works:

# concatenation
re.findall(r'\w{'+ str(count) + ',}', sarg)
# format method
re.findall(r'\w{{{},}}'.format(count), sarg)  # <-- a little clunky having to escape '{' using '{{' etc.
# use explicit counting instead of ranges: stack '\w' add '+' for "or more"
re.findall(r'\w' * count + '+', sarg)
Sophia Zeng
Sophia Zeng
2,169 Points

Hi Chris,

I don't understand why you need to add 2 '+' in here: re.findall(r'\w{'+ str(count) + ',}', sarg)

Does it stand for at least one, or it has other meaning?

Thanks!!