Python String Substitution

John Bauman john at baumanfamily.com
Thu Jan 26 20:52:36 EST 2006


"Murali" <maha.murali at gmail.com> wrote in message 
news:1138318847.465117.49040 at z14g2000cwz.googlegroups.com...
> 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?
>
One way would be to make an adapter to convert that string to a tuple:
class adapter:
    def __init__(self, dc):
       self.dc = dc
    def __getitem__(self,item):
        return self.dc[eval(item)]

Then you could use this as:
print "%((1,2))s" % adapter(d)

I wouldn't actually recommend using eval in production code, due to the 
possible security issues, but I'm sure you could replace it with some 
more/better code. This is just an idea. 





More information about the Python-list mailing list