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
Ray1 B
9,783 PointsRegular Expressions: Word Length objective
Looking at other discussions I used:
def find_words(cnt,str1):
return re.findall(r'\w{'+str(cnt)+',}',str1)
It works, but I am confused by the:
'+str(cnt)+'
In particular, step by step: why the single quotes ? why the 2 +'s ? why str(cnt) ?
Does anyone have a good explanation? I am referencing the Teachers Notes in the Counts video (Regular Expressions in Python).
1 Answer
Janessa Huppi
Front End Web Development Techdegree Graduate 42,048 PointsThe single quotes actually refer to the two string literals at the beginning and end of the regular expression.
r'\w{'
and
',}'
cnt is a parameter and its value must be added to the two string literals, hence the two plus signs. Otherwise the regular expression would interpret it as the characters: 'c', 'n', and 't'.
In this case cnt is an integer and integers can't be added to strings. So the str() method is called to convert cnt into a string.
Because of the '{' at the end of the first string literal and the '}' at the beginning of the second string literal, the function looks for words that are as long as the value of the cnt parameter.
I used Python's Regular Expression HOW TO as a reference.