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

word_length / Not sure how to solve this?

So I been trying to figure out how to approach this problem but I continue to get errors such as NoneType has no length() or Didn't get the right output. Output was []. Length was 6. I was trying to attempt to use format but I do not now to use it correctly for this instance. I think I'm over thinking this, regardless if anyone could point me in the right direction?

word_length.py
import re

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

def find_words(num, string):
    return re.findall(r"/w*{0}".format(num), string)

3 Answers

Christian Mangeng
Christian Mangeng
15,970 Points

Hi Alexander,

took me some time to figure that one out. It is surely not an easy challenge. The matching pattern you are looking for is \w{num,}. This is because with {num,} you match \w at least num times in a row. The problem is that you cannot simply add num into the matching pattern, and even .format() seems to not work here because of the curly braces of the pattern. You need to format the pattern with this method (%i because num is an integer):

def find_words(num, string):
    return re.findall(r'\w{%i,}' % (num), string)
Christian Mangeng
Christian Mangeng
15,970 Points

Saw that this one works, too. It's possibly more straightforward:

def find_words(num, string):
    return re.findall(r'\w+'* num, string)

Thank you for your help, was stuck on this for days

So why doesn't concatenation work?

def find_words(count, words):
    return re.findall(r"\w{" + re.escape(count) + r",}", words)
Christian Mangeng
Christian Mangeng
15,970 Points

Not sure exactly why it's not accepted, Rod Garland

This one seems to work:

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