Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中向正则表达式中插入字符串元素?_Python_Regex - Fatal编程技术网

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

如何在Python中向正则表达式中插入字符串元素?,python,regex,Python,Regex,假设我在python中有一个string元素。如何使用re.compile将此列表元素插入到正则表达式中 我想的是 mystring='esteban' myregex=re.compile('[mystring] is (not)? very good at python') 最终目标是在循环中完成这项工作,mystring在每次迭代中都会发生变化。因此,我不能像以前那样手动编写它 myregex=re.compile('esteban is (not)? very good at pyth

假设我在python中有一个string元素。如何使用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')

您可以使用变量名

>>> 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'
有很多方法

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']))
正如斯特凡诺·桑菲利波所说


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

myregex=re.compile({}是(不是)?非常擅长python.format(mystring))正则表达式只是一个字符串,所以它可以像任何其他字符串一样格式化和连接。只有一条建议使用原始字符串
r'my regular expression'
,这避免了转义任何特殊字符序列,如
\n
,其中只应使用第一个。第三个是可以接受的,但相当难看,第二个是不推荐的(如果您使用的是一个古老的Python版本,可能还可以),而最后一个是矫枉过正的。@StefanoSanfilippo是的,只是想给OP一个选择。编辑它以使其更好。谢谢别忘了
myregex=re.compile({mystring}是(不是)?非常擅长python.format(mystring=mystring))
@SethMMorton变量名太长了,最好用短一点的。不管怎样,好的。将其添加到list@BhargavRao同意,它太长了,但它说明了类似字典的替换是可能的。