Curious Omission In New-Style Formats

Ian Kelly ian.g.kelly at gmail.com
Sun Jul 10 03:21:40 EDT 2016


On Sat, Jul 9, 2016 at 11:54 PM, Lawrence D’Oliveiro
<lawrencedo99 at gmail.com> 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'
>
> but not in new-style formats:
>
>     >>> "{:#0.5x}".format(0x123)
>     Traceback (most recent call last):
>       File "<stdin>", line 1, in <module>
>     ValueError: Precision not allowed in integer format specifier
>
> The field width itself doesn’t give the right number of digits in this case:
>
>     >>> "{:#05x}".format(0x123)
>     '0x123'
>
> because you lose 2 characters for the “0x” prefix.

So add 2 to the field width to account for the fixed-size prefix.

>>> '{:#07x}'.format(0x123)
'0x00123'

It's specified in PEP 3101 that the precision is ignored for integer
conversions. Apparently that changed from "ignored" to "not allowed"
in 3.1, as per the documentation. I'm not sure what the reasoning was,
except perhaps that precision doesn't really make sense for integers
in the first place.



More information about the Python-list mailing list