Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does it matter to use %d over %s when formatting integers to strings in python?

Tags:

python

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'
like image 631
Lyke Avatar asked Nov 30 '22 08:11

Lyke


2 Answers

%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.

like image 178
Senthil Kumaran Avatar answered Dec 05 '22 17:12

Senthil Kumaran


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
like image 32
Keith Avatar answered Dec 05 '22 17:12

Keith