newbie question: parse a variable inside an RE?
John Machin
sjmachin at lexicon.net
Mon Dec 1 18:40:37 EST 2008
More information about the Python-list mailing list
Mon Dec 1 18:40:37 EST 2008
- Previous message (by thread): newbie question: parse a variable inside an RE?
- Next message (by thread): end of print = lower productivity ?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Dec 2, 8:56 am, "Diez B. Roggisch" <de... at nospam.web.de> wrote: > joemacbusin... 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. In fact what the OP is trying to do amounts to a convoluted version of I.startswith(newresp) which probably isn't his real requirement anyway :-(
- Previous message (by thread): newbie question: parse a variable inside an RE?
- Next message (by thread): end of print = lower productivity ?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list