Curious Omission In New-Style Formats

Lawrence D’Oliveiro lawrencedo99 at gmail.com
Sun Jul 10 01:54:48 EDT 2016


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.



More information about the Python-list mailing list