Python Regular Expressions in Python Introduction to Regular Expressions Word Length

Chuck Anderson
Chuck Anderson
2,175 Points

How do i put a variable into a raw string?

I need to find all the words, with a given length (num) or longer, in a string (str) using a regex. I can get it work with a hard coded number like this re.findall(r'\w{4,}', str) but how can I use a variable so i can have different lengths?

I've tried this re.findall(r'\w{num,}', str) and re.findall(r'\w{%num,}', str) but I get an empty list back.

word_length.py
import re

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

def find_words(c, s):
    return re.findall(r'\w{c,}', s)

3 Answers

Mark Sebeck
MOD
Mark Sebeck
Treehouse Moderator 18,394 Points

I'm sure there is a better way to do this but this did pass the challenge.

    return re.findall(r'\w{' + str(c) + ',}', s)
Mark Sebeck
Mark Sebeck
Treehouse Moderator 18,394 Points

I'm actually going to be retaking this course soon because I am reviewing Python. I'll let you know if I find something better.

Chuck Anderson
Chuck Anderson
2,175 Points

OK, thank you for the response! i didn't realize i could cast a string inside the raw string.

Mark Sebeck
Mark Sebeck
Treehouse Moderator 18,394 Points

You're welcome. If you find a cleaner way let me know. Even though it works I'm not sure it's the best way.

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 59,232 Points

Other ways to embed variable values into raw strings:

>>> import re
>>> c = 5
>>> s = "this and that alrighty to booth"
>>> re.findall(r'\w{' + str(c) + ',}', s)
['alrighty', 'booth']
>>> re.findall(r'\w{%s,}' % c, s)
['alrighty', 'booth']
>>> re.findall(r'\w{{{},}}'.format(c), s)
['alrighty', 'booth']
>>> re.findall(r'\w{{{c},}}'.format(c=c), s)
['alrighty', 'booth']
>>> re.findall(fr'\w{{{c},}}', s)
['alrighty', 'booth']
>>> 

Post back if you need more help. Good luck!!

Mark Sebeck
Mark Sebeck
Treehouse Moderator 18,394 Points

Thanks Chris! I knew there had to be a cleaner way