Both %s and %d operatorsUses decimal conversion via int() before formatting. %s can accept numeric values also and it automatically does the type conversion. In case a string is specified for %d operator a type error is returned.
In Python, string formatters are essentially placeholders that let us pass in different values into some formatted string. The %d formatter is used to input decimal values, or whole numbers. If you provide a float value, it will convert it to a whole number, by truncating the values after the decimal point.
%s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string. It is used to incorporate another string within a string. It automatically provides type conversion from value to string. The %s operator is put where the string is to be specified.
%s acts as a placeholder for the real value. You place the real value after the % operator. This method is often referred to as the "older" way because Python 3 introduced str. format() and formatted string literals (f-strings).
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))
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
%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
These are all informative answers, but none are quite getting at the core of what the difference is between %s
and %d
.
%s
tells the formatter to call the str()
function on the argument and since we are coercing to a string by definition, %s
is essentially just performing str(arg)
.
%d
on the other hand, is calling int()
on the argument before calling str()
, like str(int(arg))
, This will cause int
coercion as well as str
coercion.
For example, I can convert a hex value to decimal,
>>> '%d' % 0x15
'21'
or truncate a float.
>>> '%d' % 34.5
'34'
But the operation will raise an exception if the argument isn't a number.
>>> '%d' % 'thirteen'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str
So if the intent is just to call str(arg)
, then %s
is sufficient, but if you need extra formatting (like formatting float decimal places) or other coercion, then the other format symbols are needed.
With the f-string
notation, when you leave the formatter out, the default is str
.
>>> a = 1
>>> f'{a}'
'1'
>>> f'{a:d}'
'1'
>>> a = '1'
>>> f'{a:d}'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'd' for object of type 'str'
The same is true with string.format
; the default is str
.
>>> a = 1
>>> '{}'.format(a)
'1'
>>> '{!s}'.format(a)
'1'
>>> '{:d}'.format(a)
'1'
These are placeholders:
For example: 'Hi %s I have %d donuts' %('Alice', 42)
This line of code will substitute %s with Alice (str) and %d with 42.
Output: 'Hi Alice I have 42 donuts'
This could be achieved with a "+" most of the time. To gain a deeper understanding to your question, you may want to check {} / .format() as well. Here is one example: Python string formatting: % vs. .format
also see here a google python tutorial video @ 40', it has some explanations https://www.youtube.com/watch?v=tKTZoB2Vjuk
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