[Python-3000] Format specifier proposal

Talin talin at acm.org
Sat Aug 11 10:57:16 CEST 2007


Taking some ideas from the various threads, here's what I'd like to propose:

(Assume that brackets [] means 'optional field')

   [:[type][align][sign][[0]minwidth][.precision]][/fill][!r]

Examples:

    :f        # Floating point number of natural width
    :f10      # Floating point number, width at least 10
    :f010     # Floating point number, width at least 10, leading zeros
    :f.2      # Floating point number with two decimal digits
    :8        # Minimum width 8, type defaults to natural type
    :d+2      # Integer number, 2 digits, sign always shown
    !r        # repr() format
    :10!r     # Field width 10, repr() format
    :s10      # String right-aligned within field of minimum width
              # of 10 chars.
    :s10.10   # String right-aligned within field of minimum width
              # of 10 chars, maximum width 10.
    :s<10     # String left-aligned in 10 char (min) field.
    :d^15     # Integer centered in 15 character field
    :>15/.    # Right align and pad with '.' chars
    :f<+015.5 # Floating point, left aligned, always show sign,
              # leading zeros, field width 15 (min), 5 decimal places.

Notes:

   -- Leading zeros is different than fill character, although the two 
are mutually exclusive. (Leading zeros always go between the sign and 
the number, padding does not.)
   -- For strings, precision is used as maximum field width.
   -- __format__ functions are not allowed to re-interpret '!r'.

I realize that the grouping of things is a little odd - for example, it 
would be nice to put minwidth, padding and alignment in their own little 
group so that they could be processed independently from __format__. 
However:

   -- Since minwidth is the most common option, I wanted it to have no 
special prefix char.
   -- I wanted precision to come after minwidth, since the 'm.n' format 
feels intuitive and traditional.
   -- I wanted type to come first, since it affects how some attributes 
are interpreted.
   -- Putting the sign right before the width field also feels right.

The regex for interpreting this, BTW, is something like the following:

    "(?:\:([a-z])?(<|>|\^)?(+|-)?(\d+)(\.\d+))(/.)?(!r)?"

(Although it may make more sense to allow the fill and regex fields to 
appear in any order. In other words, any field that is identified by a 
unique prefix char can be specified in any order.)

-- Talin



More information about the Python-3000 mailing list