Assuming I don't need padding or other formatting conversion, when does it matter to use %d over %s when printing 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With