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 Word Length

kevin cleary
kevin cleary
4,690 Points

word_length.py

What is wrong with my code

import re

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

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 67,989 Points

Your regex is very close. It current finds only words of exactly count length. To find words of count length or more, you need to add a comma to the notation: {count,}

import re
def find_words(count, strang):
  return re.findall(r'\w{'+ str(count) +',}', strang)  # <-- added comma before closing brace
kevin cleary
kevin cleary
4,690 Points

Thank you very much.

Chase Frankenfeld
Chase Frankenfeld
6,137 Points

Hi Chris, can you please explain the '+ str(count) +' of the code?

I had originally done this, which from the above answer, and attempt, proves to be incorrect.

return re.findall(r'\w{count,}', string)
Chris Freeman
Chris Freeman
Treehouse Moderator 67,989 Points

Chase, there are many solutions that work for this challenge. The key is creating the string with the correct syntax.

in the solution above, I corrected the posted problem which used string concatenation to build the regex string.

str(count) converts the value in count to a string. If count had a value of 3, str(count) would return the string "3". The string concatenation would then be:

r'\w{'+ '3' +',}'

# which is the same as
r'\w{3,}'

You can use count directly in a formatted string using one of the following methods

# simple substitution
r'\w{%s,}' % count

# format method. Use '{{' and '}}' to escape braces
r'\w{{{},}}'.format(count)

# format method with named fields. Use '{{' and '}}' to escape braces
r'\w{{{value},}}'.format(value=count)