Partial string formatting?

Gonçalo Rodrigues op73418 at mail.telepac.pt
Tue Jan 21 12:47:34 EST 2003


On Tue, 21 Jan 2003 18:17:49 +0100, Max M <maxm at mxm.dk> wrote:

>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 -
>

This should return instead:

val1 - 2 - %(key3)s

As I said, if a priori I know that the formatting code is just s, the
problem is easily solved. But if I want to be completely general I'm
basically stuck because the formatting codes can have a bewildering
array of variations.

>
>regards Max M

With my best regards,
G. Rodrigues




More information about the Python-list mailing list