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.
Can you put a variable in regex Python? Use string formatting to use a string variable within a regular expression. Use the syntax "%s" % var within a regular expression to place the value of var in the location of the string "%s" .
Python's re. compile() method is used to compile a regular expression pattern provided as a string into a regex pattern object ( re. Pattern ). Later we can use this pattern object to search for a match inside different target strings using regex methods such as a re.
You can do it like so...
>>> regex2 = re.compile('.*(%s).*'%what2look4)
Or you can use format:
>>> regex2 = re.compile('.*({}).*'.format(what2look4))
Use a String format:
search = "whattolookfor"
regex2=re.compile(".*({}).*".format(search))
The {}
inside the string will be replaced with whattolookfor
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With