October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk2 min

How to Convert a Hexadecimal String to Bytes in Python

Use Python’s bytes.fromhex() to turn pairs of hexadecimal digits into bytes, with ASCII whitespace allowed between digits.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Python’s built-in bytes.fromhex() method to convert hexadecimal text into bytes. Each pair of hex digits becomes one byte, and ASCII whitespace between digits is ignored.

Convert a hex string with bytes.fromhex()

Call the method on bytes and pass the hexadecimal string:

hex_string = "2Ef0 F1f2"
data = bytes.fromhex(hex_string)
print(data)  # b'.xf0xf1xf2'

The string contains four pairs of hexadecimal digits, so the result contains four bytes. The space between pairs is allowed. Python’s built-in types documentation shows this conversion and specifies that ASCII whitespace is ignored.

Input format and whitespace

Supply two hexadecimal digits for each byte. For example, "2ef0f1f2" represents the same bytes as "2e f0 f1 f2". Since Python 3.7, bytes.fromhex() skips all ASCII whitespace, not just ordinary spaces.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do not assume the method will clean up other formatting. Prefixes such as 0x, commas, colons, or arbitrary non-hex characters are not covered by the documented whitespace behavior. If your input uses such formatting, remove or validate it deliberately before conversion rather than treating it as plain hex.

Use binascii.unhexlify() as an alternative

The standard-library binascii module also converts hexadecimal text to binary data:

import binascii

data = binascii.unhexlify("2ef0f1f2")

In the documented Python 3.10 API, unhexlify() requires an even number of hexadecimal digits; a malformed length raises binascii.Error. The Python 3.10 binascii documentation describes bytes.fromhex() as more liberal about whitespace. For typical string input—especially when whitespace may occur—bytes.fromhex() is the simpler choice.

Convert the bytes back to hexadecimal text

Use .hex() on the resulting bytes to get a string with two hexadecimal digits per byte:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
data = bytes.fromhex("2ef0f1f2")
hex_again = data.hex()
print(hex_again)  # '2ef0f1f2'

The Python built-in types documentation also describes separators for formatting the hexadecimal output.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Handle invalid input and version differences

For untrusted or externally supplied text, let conversion errors reach a suitable validation boundary or catch them there so the application can report invalid data or recover. The documented behavior does not establish one exception type for every malformed bytes.fromhex() case across Python versions, so check the documentation for the version your application supports before relying on a specific exception.

There are two relevant version notes: Python 3.7 expanded ignored whitespace to all ASCII whitespace, and Python 3.14 added support for ASCII bytes and bytes-like objects as the method’s input. If you pass anything other than a str, check that the deployed Python version supports it in the current built-in types documentation.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.