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

jfong at ms4.hinet.net jfong at ms4.hinet.net
Mon Mar 19 20:32:00 EDT 2018


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.

--Jach



More information about the Python-list mailing list