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

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 68,441 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 68,441 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)