如何将变量添加到我的 re.compile 表达式中 [英] How to add a variable into my re.compile expression
本文介绍了如何将变量添加到我的 re.compile 表达式中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我试图在文件中查找由变量 what2look4
表示的关键字.每当我运行此程序时,它都会返回空白数据.代码如下:
regex2=re.compile(".*(what2look4).*")
我认为问题在于文件被搜索 what2look4
作为字符串本身而不是该变量代表的内容.如有错误请指正,谢谢帮助.
解决方案
你可以这样做...
<预><代码>>>>regex2 = re.compile('.*(%s).*'%what2look4)或者您可以使用格式:
<预><代码>>>>regex2 = re.compile('.*({}).*'.format(what2look4))So I am trying to look through a file for a keyword that is represented by the variable what2look4
. Whenever I run this program however it keeps returning blank data. The code is as follows:
regex2=re.compile(".*(what2look4).*")
I believe the problem is that the file is being searched for what2look4
as a string in itself instead of what that variable represents. Please correct me if I'm wrong, thanks for the help.
解决方案
You can do it like so...
>>> regex2 = re.compile('.*(%s).*'%what2look4)
Or you can use format:
>>> regex2 = re.compile('.*({}).*'.format(what2look4))
这篇关于如何将变量添加到我的 re.compile 表达式中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文