str.encode()

Cross the string→bytes boundary — the counterpart to bytes.decode(). Pick your encoding carefully.

String methodPython 2.0+Live demo
Common call
name.encode("utf-8")
Returns
a bytes object
Replaces
the older `codecs.encode(s, encoding)` pattern
Watch out
default is utf-8 in Python 3 (ASCII in Python 2!); UnicodeEncodeError on out-of-range characters
str.encode(encodingencodingThe target encoding. Common: "utf-8" (universal), "ascii" (7-bit only), "latin-1" (Latin-1 / ISO-8859-1, single-byte), "utf-16", "cp1252" (Windows).type: str · default: "utf-8"="utf-8", errorserrorsError handler. "strict" (default) raises UnicodeEncodeError. "ignore" drops unmappable chars. "replace" substitutes "?" (or "\ufffd" for utf-8). "xmlcharrefreplace" and "backslashreplace" are also available.type: str · default: "strict"="strict")
bytes

Demo

Live evaluation
Try:
Inputs
stringstrthe source string
encodingstrutf-8 / ascii / latin-1
Output
'hello'.encode('utf-8')
'b\'hello\''

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

NameTypeRequiredDescription
encodingstrno ("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).
errorsstrno ("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

bytesA 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

Convert for network transmission
HTTP bodies, socket writes, and file IO in binary mode all expect bytes.
payload = json.dumps(data).encode("utf-8")
socket.send(payload)
Write to a binary file
Files opened in binary mode expect bytes, not str.
with open("out.bin", "wb") as f:
    f.write(text.encode("utf-8"))
Encode with error handler
When a lossy conversion is acceptable, use "ignore" or "replace".
ascii_only = text.encode("ascii", errors="ignore")
Round-trip with decode
encode then decode with the same encoding is an identity for successful cases.
s == s.encode("utf-8").decode("utf-8")   # True for valid Unicode

Examples

1. Basic UTF-8
"hello".encode()
Returns
b'hello'
2. Emoji in UTF-8
"hi 😀".encode()
Returns
b'hi \xf0\x9f\x98\x80'
3. Accented in UTF-8
"café".encode("utf-8")
Returns
b'caf\xc3\xa9'
4. ASCII ok
"hello".encode("ascii")
Returns
b'hello'
5. ASCII strict fails
"café".encode("ascii")
Returns
UnicodeEncodeError
6. ASCII with ignore
"café".encode("ascii", errors="ignore")
Returns
b'caf'
7. ASCII with replace
"café".encode("ascii", errors="replace")
Returns
b'caf?'
8. Latin-1 handles é
"café".encode("latin-1")
Returns
b'caf\xe9'

Pitfalls

1. ASCII cannot handle non-ASCII characters
The most common encode error. ASCII is a 7-bit encoding — anything above codepoint 127 (accents, emoji, non-Latin scripts) raises UnicodeEncodeError. If you know you might have non-ASCII, use UTF-8 or an error handler.
ASCII strict fails
"café".encode("ascii")
UnicodeEncodeError: 'ascii' codec can't encode character '\xe9'
UTF-8 handles it
"café".encode("utf-8")
b'caf\xc3\xa9'
2. Default is UTF-8 in Python 3 (was ASCII in Python 2)
A porting trap. Python 2's str.encode() defaulted to ASCII and often silently produced weird bytes. Python 3's default is UTF-8 and behavior is different — be explicit about encoding for portable code.
Assumed ASCII
text.encode()   # Python 2 default was ASCII
behavior differed by version
Explicit encoding
text.encode("utf-8")
unambiguous everywhere
3. errors="ignore" silently DROPS characters
Convenient but dangerous. A field like "José" becomes "Jos" with ignore + ASCII — silent data loss. If the data matters, log or reject; do not just ignore.
Silent loss
"José".encode("ascii", errors="ignore")
b'Jos' # lost é
Log or fail
try:
    text.encode("ascii")
except UnicodeEncodeError as e:
    log.warning(...)
error visible
4. UTF-8 byte count is NOT character count
One character can be 1-4 bytes in UTF-8. `len(s)` counts characters; `len(s.encode("utf-8"))` counts BYTES. Confusing them causes off-by-one bugs in length limits.
Miscounted length
len("café")
len("café".encode("utf-8"))
4 5 # é is 2 bytes
Pick which one
# character limit: use len(s)
# byte limit: use len(s.encode("utf-8"))
clear intent

When to use

Use it
  • 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
Reach for something else
  • 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

Complexity
O(n) — one linear scan
Return
A new bytes object; the string is unchanged
CPython impl
Objects/unicodeobject.c :: unicode_encode
Memory
Allocates one bytes object of variable size (depends on encoding)
Thread-safe
Yes — strings are immutable

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.

History

2.0
encode() introduced along with Unicode strings.
3.0
Default encoding changed from ASCII to UTF-8; str is now Unicode by default.