Printing A Python List With Hex Elements
I have this list: a_list = [0x00, 0x00, 0x00, 0x00] When I print it, I get: print a_list [0, 0, 0, 0] But I want:[0x0, 0x0, 0x0, 0x0] or [0x00, 0x00, 0x00, 0x00], it doesn't matt
Solution 1:
>>>a_list = range(4)>>>print'[{}]'.format(', '.join(hex(x) for x in a_list))
[0x0, 0x1, 0x2, 0x3]
This has the advantage of not putting quotes around all the elements, so it produces a valid literal for a list of numbers.
Solution 2:
Try the following:
print [hex(x) forx in a_list]
The output shall be something like: http://codepad.org/56Vtgofl
Solution 3:
print [hex(no) forno in a_list]
hex
function converts a number to its hexadecimal representation.
Solution 4:
For python3, use following code:
print([hex(x) forx in a_list])
Solution 5:
If you want zero padding:
", ".join("0x{:04x}".format(num) for num in a_list)
The "0x{:04x}" puts the "0x" in front of the number. The "{:04x}" part pads zeros to 4 places, printing the number in hex.
Post a Comment for "Printing A Python List With Hex Elements"