"%(a)s ... %(b)s" % {'a': foo, 'b': '%(b)s'}

Michael Hudson mwh21 at cam.ac.uk
Sat Dec 4 19:26:33 EST 1999


Gerrit Holl <gerrit.holl at pobox.com> writes:

> >>> s='%% sign, %%(email)s, %(version)s, %%%% sign'
> >>> s2=s % {'version': 1}
> >>> print s2
> % sign, %(email)s, 1, %% sign
> >>> print s2 % {'email': 'gerrit at nl.linux.org'}
> {'email': 'gerrit at nl.linux.org'}ign, gerrit at nl.linux.org, 1, % sign
> 
> kan lead to very unexspected things ;-)
> 
> This can lead to ugly Quoting hell!

Oh yes, it's not a robust neat solution. It's simple and works as well
as it does, if you get what I mean.


> But _why_ isn't this permitted:
> >>> print '%(a)s, %(b)s' % {'a': 'aaaa'}
> Traceback (innermost last):
>   File "<stdin>", line 1, in ?
> KeyError: b
> 
> Can't Python automatticaly detect there's no B so leave it blank?
> Why doesn't Python do this?

Well, you could claim that if you were writing a CGI script, you be
annoyed if you got it wrong and your web pages had 

Welcome %(uname)s! I hope you find my site useful!

all over them... I mean, there's no obvious "right" solution, so
Python picks one. As usual it is flexible enough to let you use the
other if you want it.

Cheers,
Michael




More information about the Python-list mailing list