Python bytes.fromhex(): Convert Hex Strings to Bytes
Use Python's bytes.fromhex() method to convert hexadecimal strings into bytes objects. Includes whitespace handling, ValueError cases, bytes vs bytearray choices, and practical examples.

bytes.fromhex() is the Python class method that turns a hexadecimal string into a bytes object. It's the direct answer to the common python bytes fromhex conversion task: given text like "48656c6c6f", it returns b'Hello'.
>>> bytes.fromhex("48656c6c6f")
b'Hello'The method reads pairs of hex digits and produces one byte per pair. 48 becomes H, 65 becomes e, and so on. The input is a regular str, and the result is always a new bytes object.
How bytes.fromhex() Parses Its Input
The parser is lenient about formatting in one important way: it ignores ASCII whitespace anywhere in the string. That includes spaces, tabs, and newlines.
>>> bytes.fromhex("48 65 6c 6c 6f")
b'Hello'
>>> bytes.fromhex("48\n65\t6c 6c 6f")
b'Hello'Both examples produce the same result as the single continuous string. This makes the method convenient for parsing formatted hex dumps, where bytes are often separated by spaces for readability.
Hex digits may be uppercase or lowercase. "48656c6c6f" and "48656C6C6F" are equivalent.
The parser does not accept a 0x prefix. bytes.fromhex("0x48") raises ValueError. If your input uses that prefix, strip it before calling the method.
Return Value and the bytes vs bytearray Distinction
bytes.fromhex() returns an immutable bytes object. The sibling class method bytearray.fromhex() behaves identically but returns a mutable bytearray.
>>> bytes.fromhex("48656c6c6f")
b'Hello'
>>> bytearray.fromhex("48656c6c6f")
bytearray(b'Hello')Choose bytes when the result will be used as a key, stored in a set, or passed to an API that requires immutable input. Choose bytearray when you need to modify the binary data in place after conversion.
Error Handling: When fromhex() Raises ValueError
bytes.fromhex() raises ValueError in two cases:
- The input contains a character that is not a hex digit or whitespace.
- The number of hex digits is odd, so the final digit has no pair.
>>> bytes.fromhex("48656c6c6") # odd number of digits
ValueError
>>> bytes.fromhex("48 6g 6c 6c") # 'g' is not a hex digit
ValueErrorThe call fails as a whole; you do not get a partially converted bytes object.
If you're parsing untrusted input, catch ValueError explicitly rather than letting it propagate as an unhandled exception.
def parse_hex(data: str) -> bytes | None:
try:
return bytes.fromhex(data)
except ValueError:
return NonePractical Use Cases
The most common use of bytes.fromhex() is converting hex-encoded data from text-based formats into binary form. Network protocols, configuration files, and log dumps frequently represent binary payloads as hex strings.
A typical example is parsing a MAC address:
mac = "a4:5e:60:b7:9e:21"
mac_bytes = bytes.fromhex(mac.replace(":", ""))Another common case is reading a hex dump from a file and converting it before writing it back out as binary:
with open("dump.hex") as f:
hex_data = f.read().strip()
binary = bytes.fromhex(hex_data)Performance and Memory Behavior
bytes.fromhex() runs in linear time relative to the length of the input. Each pair of hex digits requires a single byte of output, so the result is always half the length of the hex string (after whitespace is removed).
The method allocates a new bytes object every time it is called. If you convert the same constant hex string repeatedly, store the result once rather than calling fromhex() in a loop.
The parser ignores ASCII whitespace while scanning, so a compact hex string has fewer characters to process. For most code this is not a reason to change a readable format; optimize only if profiling shows this step matters.
Comparing bytes.fromhex() with Other Conversion Paths
Several other APIs can convert hex text to binary data. The right choice depends on your input format and what you need the result for.
| Conversion path | Input type | Result | Ignores whitespace | Accepts 0x prefix |
|---|---|---|---|---|
bytes.fromhex(s) | str | bytes | Yes | No |
bytearray.fromhex(s) | str | bytearray | Yes | No |
binascii.unhexlify(s) | str or bytes | bytes | No | No |
int(s, 16) | str | int | No | Yes |
binascii.unhexlify is a useful alternative when the input is already compact, but it rejects any whitespace in the input. int(s, 16) is useful when you only need a numeric value, not a byte sequence, and it accepts the 0x prefix.
For most purposes, bytes.fromhex() is the most convenient choice because its whitespace tolerance handles formatted input without preprocessing.
Edge Cases and Limitations
An empty string is valid and produces an empty bytes object:
>>> bytes.fromhex("")
b''Whitespace-only input also produces an empty result, since all characters are ignored:
>>> bytes.fromhex(" ")
b''The method does not accept 0x prefixes, so strip them first:
>>> bytes.fromhex("0x48656c6c6f".removeprefix("0x"))
b'Hello'The input must be a str. Passing bytes raises a TypeError, since the method expects a text sequence of hex digits.
For large binary payloads, consider whether you need the data in memory as a single bytes object at all. If you're streaming data, processing chunks individually avoids holding the entire decoded payload at once.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.