[Python-3000] Format specifier proposal

Eric Smith eric+python-dev at trueblade.com
Mon Aug 13 02:22:27 CEST 2007


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

For those cases where we're going to special case either conversions or 
repr, it would be convenient if the character were always first.  And 
since repr and string formatting are so similar, it would be convenient 
if they where the same, except for the "r" part.  But the "!" (or 
something similar) is needed, otherwise no format string could ever 
begin with an "r".

So, how about "!r" be leftmost for repr formatting.  The similarities 
would be:

"!r"       # default repr formatting
":s"       # default string formatting
"!r10"     # repr right aligned, minimum 10 chars width
":s10"     # convert to string, right aligned, minimum 10 chars width

Admittedly the "r" is now superfluous, but I think it's clearer with the 
"r" present than without it.  And it would allow for future expansion of 
such top-level functionality to bypass __format__.

Eric.


More information about the Python-3000 mailing list