When does it matter to use %d over %s when formatting integers to strings in python?
Assuming I don't need padding or other formatting conversion, when does it matter to use %d over %s when printi开发者_如何学运维ng numbers ?
From the snippet below, there seems to be no difference.
>>> "%d %d"%(12L,-12L)
'12 -12'
>>> "%s %s"%(12L,-12L)
'12 -12'
%s
can format any python object and print it is a string. The result that %d and %s print the same in this case because you are passing int/long object. Suppose if you try to pass other object, %s would print the str() representation and %d would either fail or would print its numeric defined value.
>>> print '%d' % True
1
>>> print '%s' % True
True
When you are clear if you want to convert longs/float to int, use %d.
There is little difference in the basic case. The %d does allow you to do numeric formatting that %s does not. There is a also a difference in type checking. If you happen to send a non-int to %d you will get an error, but %s will happily stringify whatever it gets.
Python2> "%s" % ("x",)
'x'
Python2> "%d" % ("x",)
<type 'exceptions.TypeError'> : %d format: a number is required, not str
There may be no difference in your case, but you can't do the opposite :
>>> "%d" % ("12")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str
>>> "%s" % ("12")
'12'
It depends on whether you want a decimal or a string approximation of the true value. Check out the docs.
>>> "%d %d" % (12, -12.9343)
'12 -12'
>>> "%s %s" % (12, -12.9343)
'12 -12.9343'
>>> "%f %.5f" % (12, -12.9343)
'12.000000 -12.93430'
>>> "%.5d %.5d" % (12, -12.9343)
'00012 -00012'
>>> "%.8f %.8f" % (12, -12.9343)
'12.00000000 -12.93430000'
>>> "%5.2s %5.2s" % (12, -12.9343)
' 12 -1'
If you restrict yourself to sufficiently tiny toy cases, you will find no difference - the string representation of the number 12 is indistinguishable from the string representation of the string "12".
However, even a little more complexity shows a difference. Try 12.54, for example:
>>> "%d %d"%(12.54,-12.54)
'12 -12'
>>> "%s %s"%(12.54,-12.54)
'12.54 -12.54'
and you'll see a difference. And as others have noted, while a number can be coerced into a string, a string cannot be coerced into a number.
精彩评论