On 5/12/19, Alan Gauld via Tutor <tutor@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 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)

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

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

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)
    >>> '%0.27f' % n

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.
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:

Reply via email to