[Tutor] What is this code doing? What is it?

eryk sun eryksun at gmail.com
Sun May 12 19:18:37 EDT 2019


On 5/12/19, Alan Gauld via Tutor <tutor at python.org> wrote:
>
> They are both very powerful ways of constructing output strings with
> data inserted. {} and format() has a few extra tricks once you get
> into advanced uses, but % style does most of the same things (and
> has the advantage of being used in other languages too so you only
> need to remember one style!).

IMHO, given the choice of learning only one, learn the newer
curly-brace string formatting system. It's extensible since it's based
on a __format__ special method that a type (i.e. class) can override.

Take the Decimal type, for instance. By default it supports 28 digits
of precision. For example:

    >>> from decimal import Decimal
    >>> n = Decimal('0.12340567891234056789123405669') * 10
    >>> n
    Decimal('1.234056789123405678912340567')

Decimal implements the __format__ special method with its own
implementation of the "f" format specifier, which faithfully renders
the value as a string.

    >>> '{:0.27f}'.format(n)
    '1.234056789123405678912340567'

We can also use this directly with the built-in format() function in Python 3:

    >>> format(n, '0.27f')
    '1.234056789123405678912340567'

On the other hand, if we use a string's percent formatting, its "f"
format specifier has a fixed implementation that first converts a
number to a Python float, as opposed to delegating the string
conversion to the object itself.

    >>> float(n)
    1.2340567891234058
    >>> '%0.27f' % n
    '1.234056789123405772912178691'

As you can see in the formatted output, everything after
"1.234056789123405" is wrong. This is because a CPython float is
implemented as a C double-precision value, which only has about 16
decimal digits of precision.


More information about the Tutor mailing list