Concise way to format list/array to custom(hex) string

Kurien Mathew kmathew at envivio.fr
Sat Aug 2 07:53:03 EDT 2008


Hello,

What will be a concise & efficient way to convert a list/array.array of 
n elements into a hex string? For e.g. given the bytes
[116, 111, 110, 103, 107, 97]
I would like the formatted string
0x74 0x6f 0x6e 0x67 0x6b 0x61

Is there an approach better than below:
hex = ''
for b in bytes:
     hex += ('0x%x '%b)


Thanks
Kurien
	
Test program:
import array
import sys

bytes = array.array('B')
bytes.fromstring("tongka")
print bytes
hex = ''
for b in bytes:
     hex += ('0x%x '%b)
print hex




More information about the Python-list mailing list