%s
explicitly converts the input to string. %s
, %r
and %a
are the only three placeholders that convert values. From the printf
-style formatting documentation:
's'
String (converts any Python object using str()
).
So %s
supports any object, as all Python objects support str()
conversion. %d
does not do any conversion.
The other placeholders only support specific types. You probably want to use the new string formatting syntax instead (via str.format()
or f
-strings), where conversion and formatting types have been separated. There !s
, !r
and !a
can be added to first convert the value before formatting, keeping the syntax distinct and clearer that conversion takes place.
You still can't apply the d
format to strings, of course, you'll have to explicitly convert non-integer input values to integers manually if you want to use a d
field format.
The %s
and !s
string conversion is useful for types that do not otherwise have explicit formatting support. It allows you to accept any type of object and still give it some formatting in a template string, even if only to limit the field width or set a text alignment. And only string conversion is universally supported, you can't convert arbitrary objects to integers or floats, for example.