如何在Python中将字符串元素插入正则表达式?

时间:2014-12-13 12:25:24

标签: python regex

假设我在python中有一个字符串元素。如何使用re.compile将此列表元素插入正则表达式?

我想到的是像

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

最终目标是在循环中执行此操作,并在每次迭代中更改mystring。因此,我不能手动将其写为

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

2 个答案:

答案 0 :(得分:1)

有很多方法

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']))

与Stefano Sanfilippo Said一样,

多种方式按可靠性的降序列出。第一个是最佳,最后一个是最差

答案 1 :(得分:0)

您可以使用变量名称

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

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