Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #102097

Re: .format won't display my value with 2 decimal places: Why?

From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Subject Re: .format won't display my value with 2 decimal places: Why?
Date 2016-01-26 04:23 +1100
Message-ID <mailman.222.1453742620.15297.python-list@python.org> (permalink)
References <56A1B69F.3040300@gmail.com> <em59031268-5aa7-4141-b0ba-f5de9a9f9261@andromeda> <CALwzidmWXJdFq1DbW3_zTGVeDbxW0W2BeLcyc20PXCAiGFr-1A@mail.gmail.com>

Show all headers | View raw


On Tue, Jan 26, 2016 at 3:51 AM, Ian Kelly <ian.g.kelly@gmail.com> wrote:
> On Sun, Jan 24, 2016 at 2:20 PM, MRAB <python@mrabarnett.plus.com> wrote:
>> The format method, on the other hand, belongs to the format string it's
>> attached to. In this example:
>>
>>     'The new price is {}' .format(newPrice, '.2f')
>>
>> the format string is 'The new price is {}' and you're calling its 'format'
>> method with 2 values for that string, the first being 4.0 (used) and the
>> second on being '.2f' (unused).
>>
>> What you want is:
>>
>>     print('The new price is {:.2f}'.format(newPrice))
>
> Why doesn't str.format raise an exception when passed extra positional
> arguments?

That's a very good question. I suspect the answer will have to do with
i18n and the way you can reorder arguments; if some translations don't
use a token at all, it shouldn't be a fatal error that you have to
hack around by formatting something into zero characters.

It may be worth adding a special case: if no positional selectors are
used, the number of arguments must match the number of placeholders.
For comparison, here's how Pike does things (%O is roughly equivalent
to Python's {!r}):

> sprintf("%O", 1);
(1) Result: "1"
> sprintf("%O %O", 1, 2);
(2) Result: "1 2"
> sprintf("%O", 1, 2);
Compiler Error: 1: Too many arguments to sprintf (expected 2 arguments).
Compiler Error: 1: Got     : int(2..2).
> sprintf("%[0]O", 1, 2);
(3) Result: "1"
> sprintf("%[1]O", 1, 2);
(4) Result: "2"

If you're doing i18n, you probably want to use {0} {1} anyway; and if
you're deliberately ignoring some of the parameters, it's not too much
hassle to be explicit about which parameters you're not ignoring.

IMO this would be a useful protection. You get it with percent
formatting, but currently not with .format().

ChrisA

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: .format won't display my value with 2 decimal places: Why? Chris Angelico <rosuav@gmail.com> - 2016-01-26 04:23 +1100

csiph-web