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

Regular expressions code challenge. Help.

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.

It won't pass and I can't see what I'm doing wrong.

word_length.py
import re
def find_words(a_count, a_string):
  return re.findall(r'\w{a_count,}', a_string)

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

2 Answers

Dan Johnson
Dan Johnson
40,533 Points

You'll have to use format or a similar method to do string interpolation:

Format:

regex = r"\w{{{},}}".format(count)

Old method as it's easier to read:

regex = r"\w{%d,}" % count

Thanks Dan, that worked (first example). I'm not exactly sure why.

Dan Johnson
Dan Johnson
40,533 Points

The first method looks odd since format uses {} for replacement. So you have to add extras to escape them to place the literal pair.

Brian Saunders
Brian Saunders
5,780 Points

I'm not sure why I didn't think of this myself. That totally works! Thanks.