What's the difference between %s and %d in Python string formatting?
Solution 1:
They are used for formatting strings. %s
acts a placeholder for a string while %d
acts as a placeholder for a number. Their associated values are passed in via a tuple using the %
operator.
name = 'marcog'
number = 42
print '%s %d' % (name, number)
will print marcog 42
. Note that name is a string (%s) and number is an integer (%d for decimal).
See https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting for details.
In Python 3 the example would be:
print('%s %d' % (name, number))
Solution 2:
from python 3 doc
%d
is for decimal integer
%s
is for generic string or object and in case of object, it will be converted to string
Consider the following code
name ='giacomo'
number = 4.3
print('%s %s %d %f %g' % (name, number, number, number, number))
the out put will be
giacomo 4.3 4 4.300000 4.3
as you can see %d
will truncate to integer, %s
will maintain formatting, %f
will print as float and %g
is used for generic number
obviously
print('%d' % (name))
will generate an exception; you cannot convert string to number
Solution 3:
%s
is used as a placeholder for string values you want to inject into a formatted string.
%d
is used as a placeholder for numeric or decimal values.
For example (for python 3)
print ('%s is %d years old' % ('Joe', 42))
Would output
Joe is 42 years old