简体   繁体   English

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

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

Assume I have a string element in python. 假设我在python中有一个字符串元素。 How do I insert this list element into a regular expression using re.compile ? 如何使用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. 最终目标是在每次迭代中更改mystring的循环内完成此操作。 Therefore, I cannot just write it manually as 因此,我不能只是手动将其编写为

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

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, 就像Stefano Sanfilippo Said一样,

The multiple ways are listed in decreasing order of reliability. 以可靠性从高到低的顺序列出了多种方式。 The first is the best and the last is the worst 第一个是最好的 ,最后一个是最坏的

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM