str.encode()
Cross the string→bytes boundary — the counterpart to bytes.decode(). Pick your encoding carefully.
Demo
encode() converts str → bytes using the named encoding. UTF-8 handles ALL Unicode — the safe default. ASCII only handles codepoints 0..127 — any accented letter or emoji raises UnicodeEncodeError. Latin-1 handles the first 256 codepoints (adds Western European letters), still not enough for emoji. The demo uses errors="strict", so mismatches raise the error message you would see in real code.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| encoding | str | no ("utf-8") | The target encoding. Common: "utf-8" (universal), "ascii" (7-bit only), "latin-1" (Latin-1 / ISO-8859-1, single-byte), "utf-16", "cp1252" (Windows). |
| errors | str | no ("strict") | Error handler. "strict" (default) raises UnicodeEncodeError. "ignore" drops unmappable chars. "replace" substitutes "?" (or "\ufffd" for utf-8). "xmlcharrefreplace" and "backslashreplace" are also available. |
Return value
bytes — A bytes object representing the string in the given encoding. Raises UnicodeEncodeError when the string contains characters not representable in that encoding, unless errors is set to "ignore", "replace", or another handler.
Common patterns
payload = json.dumps(data).encode("utf-8") socket.send(payload)
with open("out.bin", "wb") as f: f.write(text.encode("utf-8"))
ascii_only = text.encode("ascii", errors="ignore")
s == s.encode("utf-8").decode("utf-8") # True for valid Unicode
Examples
Pitfalls
"café".encode("ascii")
"café".encode("utf-8")
text.encode() # Python 2 default was ASCII
text.encode("utf-8")
"José".encode("ascii", errors="ignore")
try: text.encode("ascii") except UnicodeEncodeError as e: log.warning(...)
len("café") len("café".encode("utf-8"))
# character limit: use len(s) # byte limit: use len(s.encode("utf-8"))
When to use
- Preparing text for network transmission (sockets, HTTP bodies)
- Writing to a binary-mode file
- Interfacing with libraries that take bytes
- Explicit conversion when the target encoding matters
- Working in memory in Python only → str is more convenient than bytes
- You do not know what encoding to use → default to UTF-8
- Silent data loss is unacceptable → use errors="strict" and handle failures
- Byte-level manipulation — that is what bytes objects are for
Notes
FAQ
UTF-8 is the default answer — it handles every Unicode character and is the universal internet standard. Use another encoding only when interfacing with a legacy system that requires it.