Python 3.1.1 string to hex Python 3.1.1 string to hex python python

Python 3.1.1 string to hex


The hex codec has been chucked in 3.x. Use binascii instead:

>>> binascii.hexlify(b'hello')b'68656c6c6f'


In Python 3.5+, encode the string to bytes and use the hex() method, returning a string.

s = "hello".encode("utf-8").hex()s# '68656c6c6f'

Optionally convert the string back to bytes:

b = bytes(s, "utf-8")b# b'68656c6c6f'


You've already got some good answers, but I thought you might be interested in a bit of the background too.

Firstly you're missing the quotes. It should be:

"hello".encode("hex")

Secondly this codec hasn't been ported to Python 3.1. See here. It seems that they haven't yet decided whether or not these codecs should be included in Python 3 or implemented in a different way.

If you look at the diff file attached to that bug you can see the proposed method of implementing it:

import binasciioutput = binascii.b2a_hex(input)