Python String Substitution

Bengt Richter bokr at oz.net
Fri Jan 27 08:29:35 EST 2006


On 26 Jan 2006 15:40:47 -0800, "Murali" <maha.murali at gmail.com> wrote:

>In Python, dictionaries can have any hashable value as a string. In
>particular I can say
>
>d = {}
>d[(1,2)] = "Right"
>d["(1,2)"] = "Wrong"
>d["key"] = "test"
>
>In order to print "test" using % substitution I can say
>
>print "%(key)s" % d
>
>Is there a way to print "Right" using % substitution?
>
>print "%((1,2))s" % d
>
>gives me "Wrong". Is there any syntax which will allow me to get
>"Right" using % substitution?

You can modify the dict to try to convert the string to what it is
a source for, by eval, and try that as a key also, if you have no security worries
about malevolent format strings:

 >>> class D(dict):
 ...     def __getitem__(self, key):
 ...         print repr(key)
 ...         if key in self: return dict.__getitem__(self, key)
 ...         else: return self[eval(key)]
 ...
 >>> d = D()
 >>> d[(1,2)] = "Right"
 >>> d["key"] = "test"
 >>> print "%(key)s" % d
 'key'
 test
 >>> print "%((1,2))s" % d
 '(1,2)'
 (1, 2)
 Right
 >>> d[123] = 'onetwothree'
 >>> print "%(123)s" % d
 '123'
 123
 onetwothree

Note recursive printing of converted key when the first one fails.
Of course if you _also_ define the string key for Wrong, that will
succeed, so it won't get converted to get Right:

 >>> d["(1,2)"] = "Wrong"
 >>> print "%((1,2))s" % d
 '(1,2)'
 Wrong
 >>> d[(1,2)]
 (1, 2)
 'Right'

Do you have a real use case? Just curious.

Regards,
Bengt Richter



More information about the Python-list mailing list