How about his?
>>> data = struct.pack('2I',12, 30)
>>> [hex(ord(c)) for c in data]
['0xc', '0x0', '0x0', '0x0', '0x1e', '0x0', '0x0', '0x0']
The expression [item for item in sequence]
is a so called list comprehension. It's basically a very compact way of writing a simple for
loop, and creating a list from the result.
The ord()
builtin function takes a string, and turns it into an integer that's its corresponding unicode code point (for characters in the ASCII character set that's the same as their value in the ASCII table).
Its counterpart, chr()
for 8bit strings or unichr()
for unicode objects do the opposite.
The hex()
builtin then simply converts the integers into their hex representation.
As pointed out by @TimPeters, in Python 3 you would need to lose the ord()
, because iterating over a bytes object will (already) yield integers:
Python 3.4.0a3 (default, Nov 8 2013, 18:33:56)
>>> import struct
>>> data = struct.pack('2I',12, 30)
>>> type(data)
<class 'bytes'>
>>> type(data[1])
<class 'int'>
>>>
>>> [hex(i) for i in data]
['0xc', '0x0', '0x0', '0x0', '0x1e', '0x0', '0x0', '0x0']
' ' === '\x20'
,'!' === '\x21'
– Jan Dvorak Dec 27 '13 at 19:25