Shouldn't %06s zero-pad a string?

Jeff Epler jepler at unpythonic.net
Thu Feb 13 14:45:10 EST 2003


Python generally takes inspiration for the handling of %-formats from
the C standard.

Here are the results I get, confusing at first:
>>> '%06s' % 'a'
'     a'
>>> '%06s' % 3
'     3'
>>> '%06d' % 3
'000003'

Here's what my printf manual page says about '0':

       0      The value should be zero padded.  For d, i,  o,  u,
              x,  X,  a, A, e, E, f, F, g, and G conversions, the
              converted value is padded on the  left  with  zeros
              rather  than  blanks.   If  the  0 and - flags both
              appear, the 0 flag is ignored.  If a  precision  is
              given with a numeric conversion (d, i, o, u, x, and
              X), the 0 flag is ignored.  For other  conversions,
              the behavior is undefined.

so "the behavior is undefined" when the s conversion is used.
The treatment of 0 as " " (space) seems fairly useful, though.

The '%06s' % 3 case makes sense when you remember what Python will do
to produce its output:  First, it converts 3 to a string and then
formats it.

Jeff





More information about the Python-list mailing list