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 include a variable in regular expression character matching?

Hello,

How do you incorporate a variable passed to the function into a regex expression? (see code attached) for example, if i want to look for 3+ characters i would type \w{3,}. however, if i want to be able to specify the '3' as a variable passed to a function, for example {count,} where count = 3, i get an empty list. Could someone explain how to make this work?

Thanks!

Kathryn

word_length.py
import re

def find_words(count, string1):

    retrun re.findall(r'\w{count,}', string1)


find_words(3, 'boy, girl, to, from, by, bye')

2 Answers

Cheo R
Cheo R
37,150 Points

You need to convert your count variable into a string.

    a = "a"
    a + 1
    Traceback (most recent call last):
    File "python", line 1, in <module>
    TypeError: Can't convert 'int' object to str implicitly

    a = "a"
    a + str(1)
    'a1'

Changed to answer

Thanks so much!