Esteban Smith
Esteban Smith

Reputation: 95

How do I insert a string element into a regular expression in Python?

Assume I have a string element in python. How do I insert this list element into a regular expression using re.compile ?

What I have in mind is something like

mystring='esteban'
myregex=re.compile('[mystring] is (not)? very good at python')

The end goal is to do this inside a loop with mystring changing in each iteration. Therefore, I cannot just write it manually as

myregex=re.compile('esteban is (not)? very good at python')

Upvotes: 2

Views: 852

Answers (2)

Bhargav Rao
Bhargav Rao

Reputation: 52071

There are many ways

myregex=re.compile('{} is (not)? very good at python'.format(mystring))

myregex=re.compile('{s} is (not)? very good at python'.format(s=mystring))

myregex=re.compile('%s is (not)? very good at python'% (mystring))

myregex=re.compile('%(mystring)s is (not)? very good at python' % locals())

myregex=re.compile(mystring+' is (not)? very good at python')

myregex=re.compile(' '.join([mystring,'is (not)? very good at python']))

Like Stefano Sanfilippo Said,

The multiple ways are listed in decreasing order of reliability. The first is the best and the last is the worst

Upvotes: 1

nu11p01n73R
nu11p01n73R

Reputation: 26667

You can use the variable name

>>> mystring='esteban'
>>> myregex=re.compile(mystring+'is (not)? very good at python')
>>> myregex.pattern
'estebanis (not)? very good at python'

OR

>>> myregex=re.compile('%s is (not)? very good at python' %mystring)
>>> myregex.pattern
'esteban is (not)? very good at python'

Upvotes: 0

Related Questions