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

Itsa Snake
Itsa Snake
3,851 Points

What is the difference between re.findall(r"\w" * 3, data) and re.findall(r"\w{3}", data)) ?

They would appear to have the same output, i.e. show the first 3 characters of any word that is at least 3 characters long.

But how are r"\w" * 3 and the r"\w{3}" supposed to be used differently?

2 Answers

Steven Parker
Steven Parker
229,732 Points

Both of those expressions will select the same thing, and either style can be used for the challenge.
But the first form might be easier to use with a variable to control the size of the match instead of a literal.

Itsa Snake
Itsa Snake
3,851 Points

Thanks a lot. Interesting that the below does not work

count_variable = 3
print(re.findall(r"\w{count_variable}", data))

That therefore makes sense for the two different use cases (i.e. \w{3} without a variable and r"\w" *count_variable if you use one.

Another thing that gets me is all of the instructors use ' instead of ". I don't see any downside in always using ", but in some cases you cannot use '

Steven Parker
Steven Parker
229,732 Points

Just putting the name of a variable in a string doesn't cause it to be replaced by its value. There are several different ways to make it happen, but all are more complicated than using the "multiply" syntax.