Explain Codes LogoExplain Codes Logo

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

python
bytes
hex
conversion
Nikita BarsukovbyNikita Barsukov·Aug 17, 2024
TLDR

In Python 3, convert bytes to a hex string using the bytes.hex() method:

hex_string = b'example'.hex() print(hex_string) # Output: 6578616d706c65

Miss manual work? Try this approach:

hex_string = ''.join(f'{b:02x}' for b in b'example') print(hex_string) # Output: 6578616d706c65

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():

import binascii # More like 'hex-or-ASCII', amirite? hex_string = binascii.hexlify(b'example').decode('ascii') print(hex_string) # Output: 6578616d706c65

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:

import codecs # It's like a secret handshake! hex_string = codecs.encode(b'example', 'hex_codec').decode() print(hex_string) # Output: 6578616d706c65

Fancy format on demand

Python 3.8+ supports the ability to include delimiters when using bytes.hex(). It's all about style!

fancy_hex_string = b'example'.hex(':') print(fancy_hex_string) # Output: 65:78:61:6d:70:6c:65

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:

# Strings to bytes to hex... are we there yet? string = 'trip' byte_data = string.encode('utf-8') # Convert to bytes hex_string = binascii.hexlify(byte_data).decode('ascii')

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.