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:
works also with the mutable
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:
In Python 3,
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):
Starting with Python 3.4, there is a less awkward option:
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.