What's the correct way to convert bytes to a hex string in Python 3? What's the correct way to convert bytes to a hex string in Python 3? python python

What's the correct way to convert bytes to a hex string in Python 3?


Since Python 3.5 this is finally no longer awkward:

>>> b'\xde\xad\xbe\xef'.hex()'deadbeef'

and reverse:

>>> bytes.fromhex('deadbeef')b'\xde\xad\xbe\xef'

works also with the mutable bytearray type.

Reference: https://docs.python.org/3/library/stdtypes.html#bytes.hex


Use the binascii module:

>>> import binascii>>> binascii.hexlify('foo'.encode('utf8'))b'666f6f'>>> binascii.unhexlify(_).decode('utf8')'foo'

See this answer:Python 3.1.1 string to hex


Python has bytes-to-bytes standard codecs that perform convenient transformations like quoted-printable (fits into 7bits ascii), base64 (fits into alphanumerics), hex escaping, gzip and bz2 compression. In Python 2, you could do:

b'foo'.encode('hex')

In Python 3, str.encode / bytes.decode are strictly for bytes<->str conversions. Instead, you can do this, which works across Python 2 and Python 3 (s/encode/decode/g for the inverse):

import codecscodecs.getencoder('hex')(b'foo')[0]

Starting with Python 3.4, there is a less awkward option:

codecs.encode(b'foo', 'hex')

These misc codecs are also accessible inside their own modules (base64, zlib, bz2, uu, quopri, binascii); the API is less consistent, but for compression codecs it offers more control.