Print a string as hexadecimal bytes Print a string as hexadecimal bytes python python

Print a string as hexadecimal bytes


You can transform your string to an integer generator. Apply hexadecimal formatting for each element and intercalate with a separator:

>>> s = "Hello, World!">>> ":".join("{:02x}".format(ord(c)) for c in s)'48:65:6c:6c:6f:2c:20:57:6f:72:6c:64:21


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


For Python 2.x:

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

The code above will not work with Python 3.x. For 3.x, the code below will work:

':'.join(hex(ord(x))[2:] for x in 'Hello, World!')