On Fri, Jun 14, 2013 at 12:01 PM, Jim Mooney <cybervigila...@gmail.com> wrote:
> On 14 June 2013 08:23, Dotan Cohen <dotanco...@gmail.com> wrote:
>>
>> What are these two string-formatting styles called?
>> '%.3f' % x
>> '{0:.3f}'.format(x)
>
>
> The first one is a string Expression, using % as the overloaded operator
> The second one is a string method, with .format() as the method for a string
> object

The str.format method is one part of the new system; the part that
you'll usually interact with. But under the hood there's a fundamental
shift that puts the object in control of its formatting via the
__format__ special method.

This works:

    >>> from decimal import Decimal

    >>> '{0:.27f}'.format(Decimal(1).exp())
    '2.718281828459045235360287471'

or with built-in format():

    >>> format(Decimal(1).exp(), '.27f')
    '2.718281828459045235360287471'

while the old way prints the wrong value, given the Decimal object's precision:

    >>> '%.27f' % Decimal(1).exp()
    '2.718281828459045090795598298'

because it first has to be converted to a machine double-precision
float, which has 15 decimal digits of precision (15.95 to be a bit
more precise).
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to