Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Regular Expressions in Python Introduction to Regular Expressions Word Length

Itsa Snake
Itsa Snake
3,850 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
210,867 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,850 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
210,867 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.