[Tutor] (no subject)

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 9 Mar 2001 18:54:05 -0800 (PST)


On Thu, 8 Mar 2001, Glen Bunting wrote:

> I have another question in the same area.  
> 
> Here is the code that I have so far:
> >>>SERVER = popen('cut --character=5- eachName')
> >>>LOOK_FOR = popen('cut --character=9- eachName')
> RESULTS = os.system(curl --include --max-time 30 SERVER | grep LOOK_FOR')
> 
> I just need to verify that what is specified in LOOK_FOR is there or not.
> What is wrong with the last line?


I'll assume that you meant to write:

> RESULTS = os.system('curl --include --max-time 30 SERVER|grep LOOK_FOR')

(with the leading quote; be careful!)

Python doesn't automatically interpolate variables into strings --- for
all it knows, you really meant to literally say the word "SERVER" or
"LOOK_FOR".  In order to get Python to "fill in the blanks", we can do
"string interpolation":

###
mycmd_template = 'curl --include --max-time 30 %s | grep %s'
mycmd = mycmd_template % (SERVER, LOOK_FOR)  # <-- This is interpolation
results = os.system(mycmd)
###

The important part to look at is the '%' operator: this is string
interpolation.  What it does is akin to the game "Mad Libs": it fills in
wherever there's a '%s' in our string.  It takes in a template to its
self, and a tuple of the stuff it fills in to its right.

You might think that '%s' isn't quite nice: it's very position dependent.  
We can make this behave more nicely if we use string interpolation with
dictionaries:

###
mycmd_template = 'curl --include --max-time 30 %(server)s | grep \
%(look_for)s'

mycmd = mycmd_template % {'server' : SERVER,
                          'look_for' : LOOK_FOR }
###

Now, when it interpolates, it looks inside our dictionary to see what we
mean by '%(server)s' and '%(look_for)s', and fills in the blanks
appropriately.

Hope this helps!