[Tutor] String formatting

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sat, 16 Feb 2002 15:29:44 -0800 (PST)


On Fri, 15 Feb 2002, VanL wrote:

>         print '%(totalfiles)s total files, %(includedfiles)s included in 
> content scan  (%(stat1)s%(percent)s)' % vars()
>         print '%(changedfiles)s files changed (%(stat2)s%(percent)s of 
> total files, %(stat3)s%(percent)s of scanned files)' % vars()
>         print '%s total text changes' % textchanges  
> 
> 
> 
> This is giving me a keyerror for totalfiles.


Hmmm... Let's check this:

###
Python 2.2 (#1, Jan 20 2002, 01:33:14) 
[GCC 2.95.4 20011006 (Debian prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> some_global = 42
>>> def function():
...     some_local = 13
...     print "vars() is %s" % vars()
...     print "globals() is %s" % globals()
... 
>>> function()
vars() is {'some_local': 13}
globals() is {'__builtins__': <module '__builtin__' (built-in)>,
'__name__': '__main__', 'function': <function function at 0x814be0c>,
'__doc__': None, 'some_global': 42}
###


We probably may want to use some combination of both dictionaries
then.  Here's a function that may help:

###
>>> def concat_dict(d1, d2):
...     d3 = d1.copy()
...     d3.update(d2)
...     return d3
... 
>>> concat_dict({'hello': 'world'}, {'penguin': 'power'})
{'hello': 'world', 'penguin': 'power'}
###


Hope this helps!