-3

In python string formatting %s supports string, integer, and float

>>> '%s' % 'a'
'a'
>>> '%s' % 1
'1'
>>> '%s' % 1.1
'1.1'

where as %d accepts and formats only integer and %s accepts only %f

>>> '%d' % 1
'1'
>>> '%d' % 'a'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str

Why is that %s alone accepts all three and even more

Gowtham MS
  • 31
  • 3
  • %s stands for a string. Since a string can be any of those, it is possible. And for a %d, since a string value can be always taken as an integer, it is not possible. – Gimhani Sep 05 '18 at 11:30
  • 1
    Just as a hint, newer python uses new string formatting `"{} {}".format('hello', 3)` – hellow Sep 05 '18 at 11:31

1 Answers1

3

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

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343