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

Matt Joiner picture Matt Joiner · Jul 8, 2011 · Viewed 290.8k times · Source

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!

Answer

Felix Weis picture Felix Weis · Mar 22, 2016

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