On Dec 2, 8:56 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] 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 :-( -- http://mail.python.org/mailman/listinfo/python-list