Call .encode("utf-8") (or simply .encode(), since "utf-8" is the default encoding in Python 3) directly on any str object to convert Unicode text into a raw UTF-8 bytes sequence—for example, raw_bytes = text.encode("utf-8")—which is required before writing binary files, sending data over network sockets, computing cryptographic hashes (hashlib), or encoding HTTP payloads.
Basic Example
text = "Hello, دنیا! 🚀"
# 1. Recommended: Explicitly encode a `str` to UTF-8 `bytes`
utf8_bytes = text.encode("utf-8")
print(type(utf8_bytes), utf8_bytes)
# Output: <class 'bytes'> b'Hello, \xd8\xaf\xd9\x86\xdb\x8c\xd8\xa7! \xf0\x9f\x9a\x80'
# 2. `.encode()` with no arguments defaults to `"utf-8"` in Python 3:
assert text.encode() == utf8_bytes
# 3. Round-trip decoding back from UTF-8 `bytes` to `str`:
decoded_text = utf8_bytes.decode("utf-8")
print(decoded_text)
# Output: Hello, دنیا! 🚀
Key Details & Edge Cases
len(text)vs.len(utf8_bytes)(characters vs. UTF-8 byte length):len(text)counts Unicode code points (14), whereas UTF-8 is a variable-width encoding (1 to 4 bytes per code point), solen(utf8_bytes)is larger whenever non-ASCII characters or emojis are present (24bytes above). Always uselen(utf8_bytes)when setting HTTPContent-Lengthheaders or socket frame sizes.
- Handling invalid lone Unicode surrogates (
UnicodeEncodeError: 'utf-8' codec can't encode character '\ud800'):- Standard Unicode strings encode cleanly to UTF-8, except strings containing lone surrogate code points (
\ud800–\udfff, often produced byerrors="surrogateescape"on malformed filenames or broken UTF-16 pairs). Passerrors="replace"(substitutes?),errors="ignore"(drops the surrogate), orerrors="surrogatepass"when sanitizing untrusted strings:broken = "bad\ud800text" print(broken.encode("utf-8", errors="replace")) # Output: b'bad?text'
- Standard Unicode strings encode cleanly to UTF-8, except strings containing lone surrogate code points (
- Adding a UTF-8 Byte Order Mark (
"utf-8-sig") for Microsoft Excel CSV compatibility:- Standard
.encode("utf-8")emits no BOM (recommended for JSON, APIs, Linux/macOS, and web protocols). Usetext.encode("utf-8-sig")when generating CSV files opened directly in Microsoft Excel on Windows so Excel recognizes non-ASCII scripts instead of misinterpreting them as Windows-1252.
- Standard
- Avoid calling
.encode()on an object that is alreadybytes(AttributeError: 'bytes' object has no attribute 'encode'):- Python 3 enforces a strict boundary between
str(text) andbytes(binary data). If an input might already bebytes, guard withdata = data.encode("utf-8") if isinstance(data, str) else data.
- Python 3 enforces a strict boundary between
bytes(text, "utf-8")constructor alternative:- Calling
bytes(text, encoding="utf-8")produces the exact samebytesobject astext.encode("utf-8"), thoughtext.encode("utf-8")is faster (avoids global name lookup) and far more idiomatic in Python.
- Calling
Comparison of UTF-8 Encoding Options in Python
| Method / Codec | Output Type | Prepends BOM (\xef\xbb\xbf)? |
Behavior on Lone Surrogates (\ud800) |
Best Used When |
|---|---|---|---|---|
text.encode("utf-8") (Recommended) |
bytes |
No | Raises UnicodeEncodeError (errors="strict") |
Standard API payloads, sockets, hashing (hashlib.sha256), and cross-platform binary I/O. |
text.encode("utf-8", errors="replace") |
bytes |
No | Replaces invalid code points with b"?" |
Encoding user-submitted or scraped strings that may contain malformed surrogate characters. |
text.encode("utf-8-sig") |
bytes |
Yes (3-byte UTF-8 BOM) |
Raises UnicodeEncodeError |
Writing CSV or text files meant to be opened cleanly in Microsoft Excel on Windows. |
bytes(text, "utf-8") |
bytes |
No | Raises UnicodeEncodeError |
Passing encoding dynamically to the bytes() constructor (prefer .encode("utf-8") in general). |
You must log in or register to comment.
