bytes.fromhex(string) reads a str of hexadecimal digits, two per byte, and returns the matching bytes object. Upper- and lowercase digits are both accepted.
ASCII whitespace between bytes is ignored, so "de ad be ef" works (since Python 3.7 all ASCII whitespace, including newlines and tabs, is skipped). It is the inverse of hex().
bytes.fromhex() is a classmethod: call it on the class, as bytes.fromhex("..."). bytearray.fromhex() works the same way and returns a bytearray.
Syntax
Call it on the class and pass a hex string.
python
data = bytes.fromhex(hex_string)
Call
What it does
bytes.fromhex("4869")
Returns b'Hi'.
bytes.fromhex("DE AD")
Returns b'\xde\xad'.
bytes.fromhex("abc")
Raises ValueError: odd number of digits.
Whitespace may separate bytes but cannot split the two digits of one byte.
Method signatures
python
classmethod bytes.fromhex(string)
# string: str of hex digits; ASCII whitespace between bytes is ignored
Parameters
Parameter
Description
string
A str containing pairs of hex digits, optionally separated by ASCII whitespace.
Return Value
Return Value
Description
bytes
A new bytes object with one byte per pair of digits.
Python Examples
Example 1 — Turn Hex Strings into bytes
Parse a compact hex string, a spaced dump, and uppercase digits that include printable and control bytes.
python
print(bytes.fromhex("48656c6c6f"))
print(bytes.fromhex("de ad be ef"))
print(bytes.fromhex("7E 00 0A"))
Output
b'Hello'
b'\xde\xad\xbe\xef'
b'~\x00\n'
How It Works
ASCII text. 48 65 6c 6c 6f are the codes for Hello, so the repr shows letters.
Spaces allowed. Whitespace between bytes is skipped; the non-ASCII values print as escapes.
Mixed repr. 0x7E is the printable ~, 0x00 prints as \x00, and 0x0A prints as \n.
Example 2 — Valid and Invalid Hex Strings
Try four inputs and catch ValueError for the bad ones. Newlines and tabs between bytes are fine on Python 3.7+.
python
for text in ["4142", "414", "41 4G", "41\n42\t43"]:
try:
print(bytes.fromhex(text))
except ValueError:
print("invalid hex:", repr(text))