Python String Substitution

Steven D'Aprano steve at REMOVETHIScyber.com.au
Thu Jan 26 19:47:37 EST 2006


On Thu, 26 Jan 2006 15:40:47 -0800, Murali wrote:

> In Python, dictionaries can have any hashable value as a string.

No. Dictionaries can have any hashable value as a KEY. They are not
automatically converted to strings.

> 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

Yes, because the dictionary has a key which is the string "key".

> Is there a way to print "Right" using % substitution?

print "%s" % "Right"
print "%s" % d[(1,2)]
print "%s%s" % ("R", "ight")

and so on.

> print "%((1,2))s" % d
> 
> gives me "Wrong". 

Yes, because the dictionary has a key which is the string "(1,2)".


> Is there any syntax which will allow me to get "Right" using %
> substitution?

You need to change your strategy. The dictionary form of string
substitution only works with keys which are strings. Look at it this way:

print "something %(x)s something" % somedict

"something %(x)s something" is a string, so all the substrings of it are
also strings, including "x". That's pretty obvious. But the same holds if
you change the x to something else:

print "something %(123.456)s something" % somedict

"123.456" is still a string.


-- 
Steven.




More information about the Python-list mailing list