Curious Omission In New-Style Formats

Steven D'Aprano steve at pearwood.info
Mon Jul 11 12:28:13 EDT 2016


On Tue, 12 Jul 2016 01:04 am, Ian Kelly wrote:

> On Sun, Jul 10, 2016 at 6:34 PM, Lawrence D’Oliveiro
> <lawrencedo99 at gmail.com> wrote:
>> On Sunday, July 10, 2016 at 7:22:42 PM UTC+12, Ian wrote:
>>> On Sat, Jul 9, 2016 at 11:54 PM, Lawrence D’Oliveiro wrote:
>>>> In printf-style formats, you can specify the number of digits for an
>>>> integer separately from the field width. E.g.
>>>>
>>>>     >>> "%#0.5x" % 0x123
>>>>     '0x00123'
>>>>
>>> except perhaps that precision doesn't really make sense for integers
>>> in the first place.
>>
>> Except that it does make sense, as I showed in my example.
> 
> Your example showed a 3-digit number being formatted with a requested
> precision of 5 digits. The way this was done was by left-padding the
> number with 0s until there were 5 digits, 

Right.

> but still only 3 digits of precision.

Er, what? I count *five* digits in "00123", not three.

You seem to be assuming that "precision" can only refer to digits after the
decimal place, but that's a dubious proposition. That might be the way
printf interprets the precision for *floats*, but its not the way it
interprets the precision for *ints*, and who is to say that one way is
right and the other is wrong?


> If you truly wanted to format the number with a precision 
> of 5 digits, it would look like this:
> 
>     0x123.00

Er, no, because its an integer.

Now, if I remember what I was told in my physics class circa 1985 correctly:

12345678 written with a precision of five digits is 12346000;

12345678 written with a precision of five decimal places is 12345678.00000.

How should we extrapolate to the case where the precision *in digits* is
greater than the number of digits available? Well, for the "decimal places"
case, we add zeroes to the right. So for the digits case, we ought to add
zeroes to the left, which brings us back to the printf usage:

123 with five digits of precision is "00123".


And we can combine that with the overall length to pad the result with
spaces as well.

It seems to me that it would be reasonable to support this for format() too.


> It may happen to do what you want in the printf-style format, but
> calling the field "precision" is at best misleading, and there are
> other ways to accomplish the same result.

Naturally. So why bother to have .format() or % in the first place? There's
always other ways to accomplish the same result.





-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list