Partial string formatting?

Max M maxm at
Tue Jan 21 18:17:49 CET 2003

Gonçalo Rodrigues wrote:

> <string> % <mapping>
> where if a key is not present in <mapping> it just leaves it untouched?
> I thought of subclassing dict to hand out a default item, which it would
> just be the requested key wrapped in %()s. Of course this only works if
> the format code is s but not with other format codes or even more
> complicated options.

Something like this?

class MappingAdapter:

     def __init__(self, aDict):
         self.aDict = aDict

     def __getitem__(self, key):
         return str(self.aDict.get(key, ''))

ma = MappingAdapter({'key1':'val1', 'key2':2})

"%(key1)s - %(key2)s - %(key3)s" % ma

 >>> val1 - 2 -

regards Max M


hilsen/regards Max M
Fremtiden, videnskab, skeptiscisme og transhumanisme

More information about the Python-list mailing list