newbie question: parse a variable inside an RE?

Diez B. Roggisch deets at nospam.web.de
Mon Dec 1 16:56:48 EST 2008


joemacbusiness at gmail.com schrieb:
> Hi All,
> 
> How do I parse a variable inside an RE?
> What is the re.search() syntax when your
> search string is a variable?
> It's easy to parse hardcoded RE's but not
> if you use a variable.

Both are exactly equal in difficulty.
> 
> Here is my code, input and runtime:
> 
> $ cat test45.py
> #!/usr/bin/python
> 
> import re
> 
> resp = raw_input('Selection: ')
> newresp = resp.strip()
> print "you chose ", newresp
> 
> fname = open('test44.in')
> for I in fname:
> #    if re.search('^newresp', "%s"%(I)):     # returns nothing
> #    if re.search(^newresp, "%s"%(I)):       # syntax error
>     if re.search("^newresp", "%s"%(I)):      # returns nothing
>         print I,

How should python know that you want the newresp being expanded? And not 
that you want to search for the word "newresp"?


You need to use the *variable* newresp:

if re.search(newresp, I): ...

If you want to alter it to have a "^" prepended before you use it, you 
need to do so:

newresp = "^" + newresp

And as show above,

"%s" % I

is nothing but I - no need for the string-interpolation.

Diez



More information about the Python-list mailing list