Curious Omission In New-Style Formats
Terry Reedy
tjreedy at udel.edu
Mon Jul 11 16:52:00 EDT 2016
On 7/11/2016 3:27 PM, Ian Kelly wrote:
> On Mon, Jul 11, 2016 at 12:54 PM, Terry Reedy <tjreedy at udel.edu> wrote:
>> In any case, I think it an improvement to say that '0x00123' has a field
>> width of 7 rather than a 'precision' of 5.
>>
>>>>> '{:#07x}'.format(0x123) # specifiy field width
>> '0x00123'
>>>>> "%#0.5x" % 0x123 # specify int precision
>> '0x00123'
>
> It occurs to me now that this does create a challenge if the format is
> meant to support negative numbers as well:
>
>>>> '%#0.5x' % -0x123
> '-0x00123'
This expands the field from 7 to 8 chars. In running text, this is
alright. In formatted table columns, it is not.
>>>> '{:#07x}'.format(-0x123)
> '-0x0123'
Multiple alternatives
>>> '{: #08x} {: #08x}'.format(0x123, -0x123)
' 0x00123 -0x00123'
>>> '{:+#08x} {:+#08x}'.format(0x123, -0x123)
'+0x00123 -0x00123'
>>> '{0:#0{1}x} {2:+#0{3}x}'.format(0x123, 7, -0x123, 8)
'0x00123 -0x00123'
>>> n1, n2, w = 0x123, -0x123, 7
>>> '{0:#0{1}x} {2:+#0{3}x}'.format(n1, w+(n1<0), n2, w+(n2<0))
'0x00123 -0x00123'
In running text, I ight go with '+','-' prefix.
--
Terry Jan Reedy
More information about the Python-list
mailing list