Cheat sheet for the new string formatting?

random832 at fastmail.us random832 at fastmail.us
Tue Jun 9 08:29:23 EDT 2015


On Tue, Jun 9, 2015, at 08:15, Skip Montanaro wrote:
> Skip> Why don't floats support "{:.Ns}"? (I know I can use "{!s}".)
> 
> random832> Why would they? The old style didn't support %.Ns either.
> 
> Well, the old style does, though it appears the N is ignored:
> 
> >>> "%5s" % -0.00666762259822
> '-0.00666762259822'

There's no dot there. I was mistaken, though, it does work.

>>> "%.5s" % -0.00666762259822
'-0.00'

The equivalent new-style format is {!s:.5} - the reason is that !s is
fundamentally different from other formats since it performs a type
conversion rather than delegating to the argument's __format__ method.
Whereas _all_ old-style format specifiers did type conversions [see
'%.23f' % Decimal('0.1') vs '{:.23f}'.format(Decimal('0.1'))]

> One thing which seems obvious now is that since format() delegates to
> the individual types for formatting, much of the documentation of this
> stuff must now be delegated to the individual types. However, I can't
> find anything about the formatting syntax supported by
> float.__format__.  Where might I find it documented that "{:.3}" is
> synonymous with "%.3g"?

Where have you looked? Have you read
https://docs.python.org/3/library/string.html#formatspec ?

None    Similar to 'g', except that fixed-point notation, when used, has
at least one digit past the decimal point. The default precision is as
high as needed to represent the particular value. The overall effect is
to match the output of str() as altered by the other format modifiers.



More information about the Python-list mailing list