bytes.hex() returns a str (not bytes) containing two lowercase hexadecimal digits for every byte, so b"\xde\xad" becomes 'dead'.
Since Python 3.8 you can pass a one-character sep to insert between groups, and bytes_per_sep to choose the group size. A positive group size counts from the right, a negative one from the left. fromhex() converts the text back.
bytes.hex() is a method of the built-in bytes type: call it on a bytes object with dot notation, such as data.hex(...). No import is needed, and bytearray objects have the same method.
Syntax
Call it with no arguments, or with a separator and group size (Python 3.8+).
python
text = data.hex()
text = data.hex(sep)
text = data.hex(sep, bytes_per_sep)
Call
What it does
b"\xde\xad\xbe\xef".hex()
Returns 'deadbeef'.
b"\x01\x02".hex(":")
Returns '01:02'.
b"\xf0\xf1\xf2".hex("_", 2)
Returns 'f0_f1f2': groups of 2 from the right.
For uppercase digits, call .upper() on the result.
Method signatures
python
bytes.hex([sep[, bytes_per_sep]])
# returns a str; sep and bytes_per_sep need Python 3.8+
Parameters
Parameter
Description
sep
Optional (3.8+). A single character (str or bytes) placed between groups.
bytes_per_sep
Optional (3.8+). Bytes per group, default 1. Positive counts groups from the right, negative from the left.
Return Value
Return Value
Description
str
Hex digits, two per byte, optionally separated.
Python Examples
Example 1 — Show Bytes as a Hex String
Convert a four-byte value and a short ASCII message to hex, and check the result type.
python
data = b"\xde\xad\xbe\xef"
print(data.hex())
print(type(data.hex()).__name__)
print(b"Hi!".hex())
print(b"".hex() == "")
Output
deadbeef
str
486921
True
How It Works
Two digits per byte. Four bytes produce eight hex digits.
A str result. The return type is str, ready to print or store as text.
ASCII codes. H, i, and ! are 0x48, 0x69, and 0x21.
Empty input. Empty bytes give an empty string.
Example 2 — Format MAC Addresses and Grouped Hex
Use a separator for a MAC address, then group five bytes in pairs from the right and from the left.
python
mac = b"\x00\x1a\x2b\x3c\x4d\x5e"
word = b"\x01\x02\x03\x04\x05"
print(mac.hex(":"))
print(word.hex("-", 2))
print(word.hex("-", -2))
print(mac.hex().upper())
One separator per byte.hex(":") gives the familiar MAC address format.
Groups from the right. With 2, the leftover single byte ends up at the start.
Groups from the left. With -2, the leftover byte ends up at the end.
Uppercase.str.upper() on the result gives capital hex digits.
Example 3 — Print a Mini Hex Dump of a Request
Show 8 bytes per row with the offset, the hex bytes, and a printable view, like the xxd tool.
python
data = b"GET / HTTP/1.1\r\n"
for i in range(0, len(data), 8):
chunk = data[i:i + 8]
text = "".join(chr(b) if 32 <= b < 127 else "." for b in chunk)
print(f"{i:04x} {chunk.hex(' '):<23} {text}")