Why don’t we need to wrap stock[key] or prices[key] in str()?


#1

In the dictionary stock[key] and prices[key] appear to be float numbers (e.g. price of oranges is 1.5) not strings. So why don’t we need to wrap stock[key] or prices[key] in str()?

As an example, my code below seems to work, but I don’t understand why:

for key in prices:
print key
print “price: %s” % prices[key]
print “stock: %s” % stock[key]


FAQ: Learn Python: A Day at the Supermarket - Keeping Track of the Produce
#2

It would make more sense to use %f in the template, but as we can see, Python will coerce the number to a string in the above interpolation. We cannot concatenate a string and a number, but we can interpolate it. Python must be applying the str() constructor in the background.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.