简体   繁体   中英

Python print decimal in hex formatted to 4 places

I have a list of several dozen entries in decimal.

CP111 = [  
[0, 0, 0, 0, 0, 0, 0, 0],  
[126, 129, 165, 129, 189, 153, 129, 126],  
[126, 255, 219, 255, 195, 231, 255, 126],  
[108, 254, 254, 254, 124, 56, 16, 0],  
[16, 56, 124, 254, 124, 56, 16, 0],  
[56, 124, 56, 254, 254, 124, 56, 124],  
[16, 16, 56, 124, 254, 124, 56, 124],  
[0, 0, 24, 60, 60, 24, 0, 0],  
[255, 255, 231, 195, 195, 231, 255, 255],  
[0, 60, 102, 66, 66, 102, 60, 0],
];  

I need to convert the decimal to hex, then format the hex to 4 places and print it without the quotes. This is as close as I have come:

CP111 = [  
[0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0],  
[0x3e, 0x41, 0x55, 0x43, 0x55, 0x41, 0x3e, 0x0],  
[0x3e, 0x7f, 0x6b, 0x7d, 0x6b, 0x7f, 0x3e, 0x0],  
[0x38, 0x7c, 0x3e, 0x1f, 0x3e, 0x7c, 0x38, 0x0],  
[0x8, 0x1c, 0x3e, 0x7f, 0x3e, 0x1c, 0x8, 0x0],  
[0x8, 0x1c, 0x29, 0x7f, 0x29, 0x1c, 0x8, 0x0],  
[0x8, 0x1c, 0x3d, 0x7f, 0x3d, 0x1c, 0x8, 0x0],  
[0x0, 0x1c, 0x3e, 0x3e, 0x3e, 0x1c, 0x0, 0x0],  
[0xff, 0xe3, 0xc1, 0xc1, 0xc1, 0xe3, 0xff, 0xff],  
[0x0, 0x1c, 0x22, 0x22, 0x22, 0x1c, 0x0, 0x0]
];  

for char in CP111:
  print '[{}],'.format(', '.join(hex(x) for x in char))

Will get me the printed hex I need but not in the 4 wide padded format

I have tried:

print "{0:#0{1}x}".format('[{}]'.format(', '.join(hex(x) for x in font_char)),4)
print '[{}]'.format(', '.join("0x{:04x}".format(hex(x) for x in font_char)))

...and several other one line attempts that all end up with syntax errors or ValueError: Unknown format code 'x' for object of type 'str'

Maybe it's not possible to put it on one line.
I need:

CP111 = [  
[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],  
[0x3e, 0x41, 0x55, 0x43, 0x55, 0x41, 0x3e, 0x00],  
[0x3e, 0x7f, 0x6b, 0x7d, 0x6b, 0x7f, 0x3e, 0x00],  
[0x38, 0x7c, 0x3e, 0x1f, 0x3e, 0x7c, 0x38, 0x00],  
[0x08, 0x1c, 0x3e, 0x7f, 0x3e, 0x1c, 0x08, 0x00],  
[0x08, 0x1c, 0x29, 0x7f, 0x29, 0x1c, 0x08, 0x00]  
.....

Help please

这是我想出的,以防其他人需要指导:

print '[{}],'.format(', '.join('0x{:02x}'.format(x) for x in font_char))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM