Python Glossary Русский

Python 3.0+Byte sequencesfunction

bytes.fromhex

bytes — encoding

A class method that creates bytes from a hex string.

Syntax

b.fromhex(...)

The string needs an even number of hex digits or you get ValueError; case is irrelevant and ASCII whitespace between digit pairs is skipped, though whitespace inside a pair is not. It is the exact inverse of b.hex(), and bytearray.fromhex() gives you the mutable counterpart.

Examples

print(bytes.fromhex('48656c6c6f'))   # → b'Hello'
print(bytes.fromhex('48 65 6c'))   # → b'Hel'
print(bytes.fromhex('ff00'))   # → b'\xff\x00'
print(bytes.fromhex('4a2b').hex())   # → 4a2b
print(bytes.fromhex('abc'))   # → ValueError

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy