What is the correct way to convert bytes to a hex string in Python 3?
In Python 3, converting a bytes object to its hexadecimal (hex) representation is straightforward—just call the .hex()
method on the bytes object. Here’s the simplest example:
some_bytes = b"\x00\xab\xff" hex_str = some_bytes.hex() print(hex_str) # Output: 00abff
Key Points:
- No Extra Imports Required: The
.hex()
method is built into Python 3. - Returns a String: The
.hex()
method converts the bytes into a lowercase hex string without any prefixes like0x
. - Uppercase vs. Lowercase: If you prefer uppercase, simply convert the string:
hex_str.upper()
.
Alternative Method (If .hex()
Isn’t Available)
If you’re on an older Python 3 version (pre 3.5) or working with an environment that doesn’t have .hex()
, you can use the binascii
module:
import binascii some_bytes = b"\x00\xab\xff" hex_str = binascii.hexlify(some_bytes).decode('ascii') print(hex_str) # Output: 00abff
binascii.hexlify()
returns a bytes object representing the hex value..decode('ascii')
converts the resulting bytes back into a standard Python string.
Using Format Strings (Less Common)
A more manual approach might look like this, but it’s rarely needed compared to .hex()
or binascii
:
some_bytes = b"\x00\xab\xff" hex_str = "".join(f"{byte:02x}" for byte in some_bytes) print(hex_str) # Output: 00abff
Here, f"{byte:02x}"
formats
TAGS
Python
CONTRIBUTOR
TechGrind