Parse spaced hexadecimal bytes without hiding malformed pairs
A copied hexadecimal dump often separates bytes with spaces or tabs. Python bytes.fromhex accepts ASCII whitespace between complete bytes, while still requiring two hexadecimal digits per byte.
Run the example
Tested on Linux with Python 3.12.14 and Python 3.13.5. Use one Bash session and a text editor. Create a disposable working directory before saving the source:
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Save as demo_python_fromhex_byte_boundaries.py:
samples = ("41 42\t43\n", "414243", "4 1", "41\u00a042", "0x41")
for text in samples:
try:
value = bytes.fromhex(text)
except ValueError:
print(f"{text!r}: rejected")
else:
assert value == b"ABC"
print(f"{text!r}: {value.hex(' ')}")Run it:
python3 -B demo_python_fromhex_byte_boundaries.pyObserved output:
'41 42\t43\n': 41 42 43
'414243': 41 42 43
'4 1': rejected
'41\xa042': rejected
'0x41': rejectedThe first two spellings decode to the same bytes. Whitespace between the two digits of one byte is rejected. A nonbreaking space is also rejected because it is not ASCII whitespace, and the 0x prefix is not part of the accepted byte-pair notation.
Limits and input policy
Do not strip every Unicode whitespace character merely to make an input parse: that broadens the accepted format and can hide a damaged export. Define that normalization separately if the application needs it. The decoded result is bytes, not text; choose an encoding explicitly if a later step needs characters. Enforce input-size limits for external dumps.
Clean up
Remove the saved script and the empty working directory in the same Bash session:
rm -- demo_python_fromhex_byte_boundaries.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirIf the directory is not empty, inspect its contents before removing anything else.
Reference
Acknowledgements
This post was created with assistance from AI.