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 Reading Files

Hara Gopal K
PLUS
Hara Gopal K
Courses Plus Student 10,027 Points

storing regex in a variable

in the following code, i can't seem to store a re-expression in a variable. it's taking the literal value instead, any idea why ? In below example, the expression r'genre should take the value from a list named books.

books = ['romance',  'fiction ',  'young-adult',  'fantasy',  'ya',  'covers',  'best',  'children',  'science-fiction',  'history',   'non-fiction',  'teen',  'mystery',  'paranormal',  'love', ]

    for genre in books:
        re_genre = r'genre'
        match_object = re.search(re_genre, long_text)
        print(match_object)
'''

2 Answers

I'd replace the line

    re_genre = r'genre'

with

    re_genre = r'{}'.format(genre)

instead.

This answer is so late and probably solved already.

But as I'm trying to browse every question in every video to learn more, I think that these posts and answers will be very helpful for future course students.

books = ['romance',  'fiction ',  'young-adult',  'fantasy',  'ya',  'covers',  'best',  'children',  'science-fiction',  'history',   'non-fiction',  'teen',  'mystery',  'paranormal',  'love', ]

 regex_pattern = re.compile(r'genre')  
 for book in books:
        match_object = re.search(regex_pattern, book)
        print(match_object)