Print a string as hex bytes?


Question

I have this string: Hello world !! and I want to print it using Python as 48:65:6c:6c:6f:20:77:6f:72:6c:64:20:21:21.

hex() works only for integers.

How can it be done?

1
149
5/14/2016 3:37:34 AM

Accepted Answer

Your can transform your string to a int generator, apply hex formatting for each element and intercalate with separator:

>>> s = "Hello world !!"
>>> ":".join("{:02x}".format(ord(c)) for c in s)
'48:65:6c:6c:6f:20:77:6f:72:6c:64:20:21:21
215
3/4/2014 3:04:32 PM

':'.join(x.encode('hex') for x in 'Hello World!')

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon