What's the correct way to convert bytes to a hex string in Python 3?
In Python 3, convert bytes to a hex string using the bytes.hex()
method:
Miss manual work? Try this approach:
Both methods yield the hex representation directly from bytes. Congrats, you've unlocked Level 1: Hex Mastery!
Advanced techniques and use-cases
Legacy issues?
Does your ancestor's code deny the existence of bytes.hex()
? Use binascii.hexlify()
:
Why decode
? Because binascii.hexlify()
returns a bytes object, not a str
.
Using codecs
as your secret weapon
codecs
module, the Swiss army knife of encoders, for hex conversion:
Fancy format on demand
Python 3.8+ supports the ability to include delimiters when using bytes.hex()
. It's all about style!
We used colons here, but feel free to pick your fancy punctuation.
A detour: More conversion tricks
Bytes to bytes-like entities
base64 and zlib come in handy for other bytes conversions:
- base64 for safe data encoding in URLs or tattoos.
- zlib for when your data had too much to eat.
Don't forget to encode strings
Strings turning into hex? Remember to change them into bytes first:
Potential pitfalls
- Hex strings are two-faced - they're always twice as long as their byte selves.
- Decode cautiously with
binascii.hexlify()
-'ascii'
is the secret password. bytes.encode('hex')
is a party crasher at the Python 3 club.
Was this article helpful?