Given a string in hexadecimal form:
hex_string = '0f'
How to convert the hex string to a bytes object in Python?
# Output: b'\x0f'
Here are a few examples:
|Hex String||Bytes Object|
Hex String to Bytes using bytes.fromhex(hex_string)
To convert a hexadecimal string to a
bytes object, pass the string as a first argument into
bytes.fromhex(hex_string) method. For example,
Here’s a minimal example:
hex_string = 'ff' print(bytes.fromhex(hex_string)) # b'\xff'
🌍 Recommended Tutorial: How to Convert Hex String to Integer in Python
And here’s how you can convert the additional examples shown above:
>>> bytes.fromhex('01') b'\x01' >>> bytes.fromhex('0101') b'\x01\x01' >>> bytes.fromhex('04') b'\x04' >>> bytes.fromhex('01 0a') b'\x01\n' >>> bytes.fromhex('01 02 0e 0f 0f') b'\x01\x02\x0e\x0f\x0f' >>> bytes.fromhex('0f0f') b'\x0f\x0f' >>> bytes.fromhex('ff') b'\xff'
Convert Hex String with Prefix ‘0x’ to Bytes
If your hex string has a prefix
'0x' in front of it, you can convert it into a bytes object by using slicing operation
hex_string[2:] to get rid of the prefix before converting it using
hex_string = '0x0f' print(bytes.fromhex(hex_string[2:])) # b'\x0f'
If you don’t know slicing well enough in Python, feel free to check out my in-depth tutorial here:
🌍 Recommended Tutorial: Python Slicing Ultimate Guide
[Fix] Value Error Non-Hexadecimal Number in fromhex()
Note that if you don’t get rid of the string hex prefix
'0x', you run in the
ValueError: non-hexadecimal number found in fromhex() arg at position 1.
>>> bytes.fromhex('0xff') Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> bytes.fromhex('0xff') ValueError: non-hexadecimal number found in fromhex() arg at position 1
You can fix this
ValueError: non-hexadecimal number found in fromhex() arg at position 1 by getting rid of the
'0x' prefix using slicing
hex_string[2:] before passing it into the
Convert Hex String to ByteArray
A simple way to convert a hexadecimal string
hex_string to a
bytearray type is to use the
bytearray.fromhex(hex_string) method. For example,
bytearray.fromhex('deadbeef') returns the
Here’s a minimal example:
hex_string = 'deadbeef' print(bytearray.fromhex(hex_string)) # bytearray(b'\xde\xad\xbe\xef')
🌍 Recommended Tutorial: How to Convert a Hex String to a Bytearray Object in Python?
After reading this, you may wonder:
What’s the Difference Between bytearray and bytes?
The difference between
bytes types is that
bytes is an immutable version of
bytearray. So you can modify an object of the latter but not of the former.
For example, let’s create both types from the same
hex_string as learned before:
hex_string = 'deadbeef' my_bytes = bytes.fromhex(hex_string) my_bytearray = bytearray.fromhex(hex_string)
Next, you’ll change the
my_bytearray variable — no problem:
print(my_bytearray) # bytearray(b'\xde\xad\xbe\xef') # Modify bytearray is possible my_bytearray = 3 print(my_bytearray) # bytearray(b'\x03\xad\xbe\xef')
But what happens if you try to modify the
my_bytes variable? An error
TypeError: 'bytes' object does not support item assignment!
>>> my_bytes = 3 Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> my_bytes = 3 TypeError: 'bytes' object does not support item assignment
To fix this error, don’t change the bytes type in your code snippet or use a mutable
bytearray instead of an immutable
🌍 Recommended Tutorial: Mutable vs Immutable Objects in Python
Where to Go From Here
Thanks for reading through the whole tutorial—I’m happy and grateful that you visited us on the Finxter blog because my mission is to help coders like you reach their goals faster.
I believe in the transformative power we coders have to change the world and make it more efficient!
If you want to keep improving your skills, feel free to check out my free email academy and download Python Cheat Sheets here:
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.