"%(a)s ... %(b)s" % {'a': foo, 'b': '%(b)s'}: SOLUTION
John Mitchell
johnm at magnet.com
Mon Dec 6 11:30:24 EST 1999
On 5 Dec 1999, Michael Hudson wrote:
> 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
Try this:
from UserDict import UserDict
class FormatDict(UserDict):
default = ''
def __getitem__(self, key):
return self.data.get(key, self.default)
d = FormatDict()
d.update( {'name': 'John'} )
print 'You, %(name)s, rule.' % d
# output: "You, John, rule."
del d['name']
d.default = "MISSING"
print 'You, %(name)s, rule.' % d
# output: "You, MISSING, rule."
This type of solution is also useful for combining multiple dictionaries
into one, or other types of convenient trickery.
- j
It is difficult to produce a television documentary that is both incisive
and probing when every twelve minutes one is interrupted by twelve dancing
rabbits singing about toilet paper. --Rod Serling
More information about the Python-list
mailing list