{:2X} didn't output what I expected

Chris Angelico rosuav at gmail.com
Mon Mar 19 20:58:21 EDT 2018


On Tue, Mar 20, 2018 at 11:32 AM,  <jfong at ms4.hinet.net> wrote:
> Chris Angelico於 2018年3月20日星期二 UTC+8上午8時06分05秒寫道:
>> On Tue, Mar 20, 2018 at 10:46 AM,  <jfong at ms4.hinet.net> wrote:
>> > D:\Temp>py
>> > Python 3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 19:28:18) [MSC v.1600 32 bit (Intel)] on win32
>> > Type "help", "copyright", "credits" or "license" for more information.
>> >>>> '{:02X}'.format(256)
>> > '100'
>> >>>>
>> > What I expected is '00'. Am I wrong?
>> >
>>
>> Python avoids losing data. If you really want to enforce that this is
>> two characters long, you can either restrict the data first (maybe
>> with "% 256"), or trim the resulting string:
>>
>> >>> '{:02X}'.format(256)[-2:]
>> '00'
>>
>> ChrisA
>
> I had overlooked the document there it says "width ... defining the minimum field width...'. I was wrong, it's not a demand. Thank you, ChrisA.

Yep. It's a policy that goes back a long way. These kinds of width
markers are often used for columnar data; but if something doesn't
fit, it's far better to push the column out a bit (ugly) than to chop
off a digit (loss of data, especially bad if it trims from the front).
So if you actually DO want that, you need to specifically request it.

ChrisA



More information about the Python-list mailing list