Print a string as hexadecimal bytes

I have this string: Hello, World! and I want to print it using Python as '48:65:6c:6c:6f:2c:20:57:6f:72:6c:64:21'.

hex() works only for integers.

How can it be done?


Solution 1:

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

Solution 2:

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