[Python-3000] Format specifier proposal

Andrew James Wade andrew.j.wade at gmail.com
Mon Aug 13 01:58:56 CEST 2007


On Sat, 11 Aug 2007 01:57:16 -0700
Talin <talin at acm.org> wrote:

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

Most custom formatting specs will probably end up putting width,
padding and alignment in their own little group and will delegate
those functions to str.__format__. Like so:

:>30/.,yyyy-MM-dd HH:mm:ss

def __format__(self, specifiers):
    align_spec, foo_spec = (specifiers.split(",",1) + [""])[:2]
    ... format foo ...
    return str.__format__(formatted_foo, align_spec.replace("foo", "s"))

(I would suggest allowing ,yyyy-MM-dd as a short form of :,yyyy-MM-dd).

I suspect there will be few cases where it makes sense to intermingle
the width/alignment/padding fields with other fields. 

I would move !r to the start of the formatting specification; it should be
prominent when it appears, and format will want to find it easily and
unambiguously rather than leaving it to boilerplate in each __format__
method.

-- Andrew


More information about the Python-3000 mailing list