Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk3 min

How to Convert a String to Bytes in Python

Convert Python text to bytes with str.encode(), choose the encoding your destination expects, and decode with the matching encoding.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Call str.encode() to convert Python text into bytes. For example, text.encode("utf-8") returns the text encoded as UTF-8. Choose the encoding expected by the file format, protocol, or API receiving the bytes; UTF-8 is a common choice when the destination supports it.

Convert a Python string with encode()

In Python 3, a str is Unicode text, while bytes is a sequence of encoded bytes. Encoding turns text into bytes using a specified character encoding, also called a codec.

text = "Hello, world!"
data = text.encode("utf-8")

print(data)        # b'Hello, world!'
print(type(data))  # <class 'bytes'>

The displayed b'...' is Python’s representation of a bytes value; it does not mean the original text has become a different string. Python’s str.encode() defaults to UTF-8 if you omit the encoding, but specifying it makes the code’s intended format clear.

Choose the encoding the destination expects

Use the receiving system’s required encoding, not simply whichever encoding is most familiar. UTF-8 is widely used for interchange and can represent all Unicode code points. Plain ASCII text is valid UTF-8, but characters outside ASCII may take multiple bytes, so the byte count can exceed the character count.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
text = "café"
data = text.encode("utf-8")
restored = data.decode("utf-8")

assert restored == text
print(data)  # b'cafxc3xa9'

The é character is represented by more than one byte in UTF-8. If a legacy interface specifically requires Latin-1, use that encoding instead; Latin-1 only maps code points U+0000 through U+00FF. The Python Software Foundation’s official Unicode HOWTO and codecs documentation describe these encoding behaviors and the importance of matching the format expected by the destination.

text = "café"
utf8_data = text.encode("utf-8")
latin1_data = text.encode("latin-1")  # only when required by the destination

Handle characters an encoding cannot represent

By default, encoding uses the strict error policy: Python raises UnicodeEncodeError if the selected encoding cannot represent a character. For example, ASCII cannot encode é, and Latin-1 cannot encode characters outside its range.

text = "café"
text.encode("ascii")  # raises UnicodeEncodeError

The errors argument can change how encoding failures are handled. For example, ignore omits unencodable characters and replace substitutes a replacement character. These strategies can discard or alter information, so use them only when that loss is acceptable to the application.

text.encode("ascii", errors="replace")  # b'caf?'

Decode bytes with the matching encoding

To turn encoded bytes back into text, call decode() with the encoding used to create them—or the encoding declared by the source format. If the encoding is unknown, bytes cannot in general be reliably interpreted as the original text.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
data = "café".encode("utf-8")
text = data.decode("utf-8")

Python does not automatically convert between str and bytes when you combine them. Encode or decode explicitly at the boundary where text and binary data meet; otherwise, operations that mix the types can raise TypeError.

Use text I/O for ordinary text files

If your goal is to read or write a text file, use Python’s text I/O and specify an encoding rather than manually encoding every value. Text I/O performs the necessary decoding when reading and encoding when writing.

with open("notes.txt", "w", encoding="utf-8") as file:
    file.write("café")

Use binary I/O when the application needs to work with bytes directly—for example, when handling a binary format or passing encoded data to an interface that explicitly expects bytes. The Python Software Foundation’s Unicode HOWTO recommends working with Unicode strings internally, decoding input as early as practical and encoding output at the end.

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

Do not use bytes(text) without an encoding

The bytes constructor requires an encoding when its input is a string. For normal string-to-bytes conversion, write text.encode("utf-8"), or provide the encoding explicitly to the constructor:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
text = "Hello"
data = bytes(text, encoding="utf-8")

A string of 0s and 1s is still text

If your string contains characters such as "01001000", encode() converts those characters into bytes; it does not interpret the digits as a binary number or automatically turn them into the corresponding words. To interpret a bit string, you need to define what those bits represent and how they are grouped and decoded.

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.

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
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

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.