[CentralOH] Tip for string interpolation

Daniel 'Dang' Griffith pythondevdang at lazytwinacres.net
Thu Aug 9 23:19:31 CEST 2007


As an aside (if you can have an aside at the beginning), I've never 
really liked the name "string interpolation". I usually just call it 
"the string formatting operator". But anyway...

I came across a bunch of good Python tips at
"<http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html>http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html", 
and got excited about one in particular, and wanted to share my 
interpretation of the string interpolation tip. It was new to me, and 
I am not taking credit for it. I'm just sharing it, in case we run 
around in different circles, as we reinvent different wheels.

No doubt, you've done this kind of thing, to print or evaluate a 
string containing some formatted values:

a = 'Three'
b = 5
print "A=%s, B=%d" % (a, b)

And, you might also have used a dictionary to hold some values, and 
then used that dictionary in a similar manner. Note that when using a 
dictionary, you put the key name between parentheses, between the % 
sign and the type (s, d, l, etc):

mydict = {'a': 'Three', 'b': 5}
print "A=%(a)s, B=%(b)d" % mydict

But here's one I learned from this tip. If the variables are in the 
same namespace, you can just refer to that dictionary:

a = 'Three'
b = 5
print "A=%(a)s, B=%(b)d" % locals()
(or if the code is within a class, print "A=%(a)s, B=%(b)d" % self.__dict__)

In other words, if you want to print the values of some variables, 
don't bother enumerating them as in style 1, or maintaining a 
separate dictionary, as in style 2.

I hope someone else gets excited about this little tidbit as I did. 
In hidhsight, it's obvious, but I definitely didn't realize it, and 
I've been Pythoning for a few years.
     --dang
----------------------------------------
A noble spirit embiggens the smallest man.
     --Jebediah Springfield
----------------------------------------




More information about the CentralOH mailing list