How to add a variable to re.compile expression

So, I'm trying to view the file for a keyword that is represented by a variable what2look4. Whenever I run this program, it saves the returned data. The code is as follows:

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

I believe that the problem is that the file is looking what2look4as a string in itself, and not what this variable represents. Please correct me if I am wrong, thanks for the help.

+4
source share
2 answers

You can do it like this ...

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

Or you can use format :

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

:

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

{} whattolookfor

+4

Source: https://habr.com/ru/post/1547630/


All Articles