What's the correct way to convert bytes to a hex string in Python 3?
I see claims of a bytes.hex
method, bytes.decode
codecs, and have tried other possible functions of least astonishment without avail. I just want my bytes as hex!
What's the correct way to convert bytes to a hex string in Python 3?
I see claims of a bytes.hex
method, bytes.decode
codecs, and have tried other possible functions of least astonishment without avail. I just want my bytes as hex!
Since Python 3.5 this is finally no longer awkward:
and reverse:
works also with the mutable
bytearray
type.If you want to convert b'\x61' to 97 or '0x61', you can try this:
Reference:https://docs.python.org/3.5/library/struct.html
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,
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):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.
it can been used the format specifier
%x02
that format and output a hex value. For example:works in Python 3.3 (so "hex_codec" instead of "hex").
OK, the following answer is slightly beyond-scope if you only care about Python 3, but this question is the first Google hit even if you don't specify the Python version, so here's a way that works on both Python 2 and Python 3.
I'm also interpreting the question to be about converting bytes to the
str
type: that is, bytes-y on Python 2, and Unicode-y on Python 3.Given that, the best approach I know is:
The following assertion will be true for either Python 2 or Python 3, assuming you haven't activated the
unicode_literals
future in Python 2:(Or you can use
''.join()
to omit the space between the bytes, etc.)