Use the built-in .encode() string method (defaulting to UTF-8) or the bytes() constructor to convert a Python 3 str into a bytes object. Because Python 3 strings are sequences of Unicode characters while files and network sockets transmit raw bytes, encoding is required whenever writing text to binary streams.
Basic Example
# 1. Define a Unicode string
text = "Hello, Python! 🐍"
# 2. Encode to bytes using UTF-8 (default encoding in Python 3)
byte_data = text.encode("utf-8")
print(byte_data) # Output: b'Hello, Python! \xf0\x9f\x90\x8d'
print(type(byte_data)) # Output: <class 'bytes'>
Key Details & Parameters
- Explicit
encodingargument: Whiletext.encode()defaults to"utf-8"in Python 3, explicitly passing"utf-8"makes your intent clear and prevents bugs if porting or reading code. - Handling unencodable characters (
errors): If you encode into a restricted character set like"ascii"or"latin-1"that lacks certain Unicode characters, Python raises aUnicodeEncodeErrorby default. Control this behavior with theerrorsparameter:greeting = "Café" # Strict (default): raises UnicodeEncodeError for 'é' # greeting.encode("ascii") # Ignore unencodable characters print(greeting.encode("ascii", errors="ignore")) # Output: b'Caf' # Replace unencodable characters with '?' print(greeting.encode("ascii", errors="replace")) # Output: b'Caf?' - Alternative
bytes()constructor: Callingbytes(text, encoding="utf-8")produces the exact same result astext.encode("utf-8"), though.encode()is generally preferred as more idiomatic. - Decoding back to a string: To reverse the operation and convert
bytesback into astr, call.decode("utf-8")on thebytesobject.
Common Encodings & Methods
| Approach / Encoding | Syntax | Behavior | Best Used When |
|---|---|---|---|
UTF-8 (.encode()) |
s.encode("utf-8") |
Supports all Unicode characters (1–4 bytes per char) | Web APIs, JSON, files, and modern cross-platform apps. |
| ASCII | s.encode("ascii") |
Supports only 7-bit ASCII characters (0–127) |
Legacy protocols or strict ASCII validation. |
| UTF-16 / UTF-32 | s.encode("utf-16") |
Fixed/variable multi-byte encoding with BOM | Interfacing with Windows APIs or Java/C# systems. |
bytes() Constructor |
bytes(s, "utf-8") |
Equivalent to s.encode("utf-8") |
Explicit type-casting style or working with byte buffers. |
You must log in or register to comment.
