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

word_length.py

For the word_length.py challenge, I was tripped up by trying to put a variable in brackets after \w. The below works, but I have two questions.

  1. Why do I have to use formatting? Why can't I do \w{count,} ?
  2. I feel like there's an extra set of curly braces. Why can't I do r'\w{{},}'.format(count1) ?
import re

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

def find_words(count1, str1):
    my_list = []
    my_list.extend(re.findall(r'\w{{{},}}'.format(count1), str1))
    return my_list

1 Answer

Steven Parker
Steven Parker
243,199 Points

The reason why "\w{count,}" doesn't work is because the word "count" would become part of the regex, and that doesn't have the meaning you intended. Instead of the word "count" itself, you want to put the value of the count variable there. The formatting allows you to include the value into the regex string.

The extra curly braces perform character escaping. Since a single curly brace represents the beginning of a token for "format" to substitute, two together are used to represent one actual curly brace in the string.

Thanks!