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

How to put a variable into the {} with re

So if I have {count} my code does not work... but if I take it into another interpreter I can see it does work when I have a value e.g. {4}

How come I pass the count variable into this {} ?

word_length.py
import re

# EXAMPLE:
# >>> find_words(4, "dog, cat, baby, balloon, me")
# ['baby', 'balloon']
def find_words(my_count, my_string):
  return re.findall(r'\w{my_count}', my_string) 

2 Answers

There's a more concise and consequently more opaque alternative to .format that does work here: return re.findall(r'\w{%d,}' % my_count, my_string)

There's a manageable tutorial here. I didn't think the Python documentation was very clear on this one.

Chase Marchione
Chase Marchione
155,055 Points

Hi David,

You'll want to explicitly convert my_count to a string, and place it outside of the quotes (when it's within quotes, the compiler interprets it as literal characters rather than a variable).

return re.findall(r'\w{' + str(my_count) + ',}', my_string)

Hope this helps!

Ahhh, I had tried a conversion- but to int I tried !!

It does work CJ Marchione- but I don't think that is the only way this can be done, it is way too hacky to be the desired approach !!