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 DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk3 min

Convert a String to a Byte Array in Python

Convert Python text with str.encode(), then choose immutable bytes, mutable bytearray, or a list of integer byte values as your output.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use str.encode() to turn Python text into bytes. For a mutable byte array, wrap the result in bytearray:

text = "café"
data = text.encode("utf-8")                 # bytes
mutable_data = bytearray(data)              # bytearray
values = list(data)                         # list of integers

Choose the output type your code needs, and specify the text encoding—usually UTF-8—so the bytes can be interpreted correctly.

Choose the result type you need

Python str objects hold text; bytes and bytearray hold encoded binary data. Encoding is the step that represents text as bytes. Python’s built-in type documentation describes these types and str.encode().

Result How to create it What it is for
bytes text.encode("utf-8") Immutable binary data; the usual choice for files, network protocols, and APIs that accept bytes.
bytearray bytearray(text.encode("utf-8")) Mutable binary data when bytes need to be changed in place.
list of integers list(text.encode("utf-8")) One integer from 0 through 255 for each encoded byte; use when an interface specifically expects integer values.

In Python, “byte array” can mean a mutable bytearray, but some callers use it loosely to mean bytes in general. Check what the receiving function requires: bytes, bytearray, and a list of integers are different types.

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

Encode a string as bytes

Call encode() on the string. UTF-8 is Python’s default encoding for this method, but stating it explicitly makes the intended representation clear:

text = "Hello, 世界"
encoded = text.encode("utf-8")
print(type(encoded))  # <class 'bytes'>

UTF-8 can represent every Unicode code point. ASCII characters use one byte, while many other characters use more. As a result, the number of encoded bytes may differ from the number of characters in the string. See the Python Unicode HOWTO for an explanation of Unicode and UTF-8.

Make the bytes mutable or inspect their values

Convert to a mutable bytearray

Pass the encoded bytes to bytearray() when you need to edit the binary data:

text = "Hello, 世界"
mutable = bytearray(text.encode("utf-8"))
mutable[0] = ord("h")

The original string is unchanged; the assignment changes the first byte in the mutable array.

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

Get one integer per byte

Use list() if an API or debugging task needs integer byte values:

encoded = "Aé".encode("utf-8")
values = list(encoded)
print(values)  # [65, 195, 169]

The two displayed characters produce three UTF-8 bytes, so the list has three values. A list is not itself a byte buffer and is usually unnecessary when the consumer accepts bytes or bytearray.

Choose an encoding that matches the receiver

Use UTF-8 for general text interchange unless a file format, API, or legacy protocol requires another encoding. If a specification requires a legacy encoding, name it rather than relying on an environment-dependent assumption. For example, Latin-1 maps code points U+0000 through U+00FF; a character outside that range cannot be encoded with it under strict handling. Python’s codecs documentation describes encodings and UTF-8 variants.

text = "café"
encoded = text.encode("latin-1")

The default error policy is strict: if the selected encoding cannot represent a character, Python raises UnicodeEncodeError. You can request errors="ignore" or errors="replace", but these policies drop or substitute unrepresentable text. Use them only when that change is acceptable for the data.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Decode bytes back into text

To recover text, decode the bytes using the same encoding used to create them:

text = "Hello, 世界"
encoded = text.encode("utf-8")
restored = encoded.decode("utf-8")

str(encoded) is not a substitute for decoding. It gives a representation of the bytes object rather than interpreting those bytes as text.

UTF-8 and Base64 are different operations

UTF-8 encodes Unicode text as bytes. Base64 takes existing binary data and represents it using printable ASCII characters. Base64 does not choose how text should be encoded; if you need Base64 text, first encode the string with the character encoding required by your format, then apply Base64 to those bytes.

Use a UTF-8 BOM only when required

Ordinary UTF-8 does not require a byte-order mark (BOM). Python’s utf-8-sig variant writes a BOM when encoding and skips it at the start when decoding. Use that variant only when the receiving file format or application expects the signature.

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

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 *

Free tools Windows power users keep installed

One-click scans. No signup required.

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.