[Python-Dev] transitioning from % to {} formatting

Vinay Sajip vinay_sajip at yahoo.co.uk
Thu Oct 8 16:16:18 CEST 2009


Nick Coghlan <ncoghlan <at> gmail.com> writes:

> Vinay's problem above is due to using the wrong alignment flag: ">",
> which says to right align everything, instead of "=", which says to left
> align the sign character and the numeric prefix with the fill character
> inserted in the middle. In this particular case he could also use the
> zero-padding shortcut which leaves out the alignment flag altogether
> (and implies a "0=" alignment format).
> 
[snip]
> Note that, since percent formatting doesn't allow specification of the
> fill characters or the field alignment, translations should probably
> rely on the simple field width specifier, optionally selecting zero
> padding by preceding it with a zero. It should never be necessary to use
> the full alignment spec for translated formats.
> 
> The other thing to keep in mind is that brace formatting is fussier
> about the order of things - items *must* appear in the order they are
> listed in PEP 3101 (i.e. if wanting a zero padded field with leading
> sign and numeric prefix, you must write "+#0"). Percent format, on the
> other hand, allows the "#", "+" and "0" to be placed in any order you
> like (although they must appear before the field width definition,
> precision specifier and type code).
> 
> As far as I can see, that leaves the prefixing of octal numbers ("0o" vs
> "0") as the only true incompatibility between percent formatting and
> brace formatting, and even for those the incompatibility is limited to
> cases where a field width is specified without leading zeroes or a sign
> character is specified. In other cases, the translation can just stick a
> leading literal "0" in front of the field in the brace formatting string.

Helpful analysis there, Nick, thanks. Bonzer ;-)

There's also the corner case of things like

%#.0f

which, when asked to format 3e100, will print

3.e+100

whereas the translated format {0:.0f}, will print

3e+100

for the same value.

BTW I sent Eric a private mail re. the "0o" versus "0" issue, to see if it was
worth raising an enhancement request on the bug tracker using "O" to generate
compatible rendering for octals.

Regards,

Vinay Sajip



More information about the Python-Dev mailing list