These are all informative answers, but none of them fully understood the difference between %s and %d .
%s tells the formatter to call the str() function for the argument, and since by definition we are casting a string to a value, %s essentially just executes str(arg) .
%d on the other hand, calls int() for the argument before calling str() , for example, str(int(arg)) , this will call both int and str .
For example, I can convert a hexadecimal value to decimal,
>>> '%d' % 0x15 '21'
or cut the float.
>>> '%d' % 34.5 '34'
But the operation will throw an exception if the argument is not a number.
>>> '%d' % 'thirteen' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: %d format: a number is required, not str
Thus, if the goal is simply to call str(arg) , then %s enough, but if you need additional formatting (for example, decimal floating-point formatting) or another cast, then other format characters are needed.
In f-string notation, when you are not using a formatter, str used by default.
>>> a = 'some_string' >>> f'{a:s}' 'some_string' >>> a = 'some_string' >>> f'{a}' 'some_string'
The same is true for string.format ; the default is str .
>>> '{}'.format(a) 'some_string' >>> '{!s}'.format(a) 'some_string'
Wyrmwood May 30 '19 at 16:23 2019-05-30 16:23
source share