如何将变量添加到我的re.compile表达式中

时间:2014-07-08 17:20:00

标签: python regex variables python-2.7

所以我试图通过一个文件来查找由变量what2look4表示的关键字。每当我运行此程序时,它会一直返回空白数据。代码如下:

regex2=re.compile(".*(what2look4).*")

我认为问题在于,文件正在搜索what2look4作为字符串本身而不是该变量所代表的内容。如果我错了,请纠正我,谢谢你的帮助。

2 个答案:

答案 0 :(得分:11)

你可以这样做......

>>> regex2 = re.compile('.*(%s).*'%what2look4)

或者您可以使用format

>>> regex2 = re.compile('.*({}).*'.format(what2look4))

答案 1 :(得分:4)

使用String format

search = "whattolookfor"
regex2=re.compile(".*({}).*".format(search))

字符串中的{}将替换为whattolookfor