str.encode()
str.encode(encoding='utf-8', errors='strict') Returns:
bytes · Updated March 13, 2026 · String Methods strings encoding bytes unicode
The encode() method converts a string to bytes using a specified character encoding. This is essential when working with file I/O, network communication, or any context requiring byte data instead of Unicode text.
Syntax
str.encode(encoding='utf-8', errors='strict')
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
encoding | str | 'utf-8' | The encoding to use (e.g., ‘utf-8’, ‘latin-1’, ‘ascii’, ‘cp1252’) |
errors | str | 'strict' | How to handle encoding errors (‘strict’, ‘ignore’, ‘replace’, ‘backslashreplace’, ‘xmlcharrefreplace’) |
Examples
Basic usage
text = "Hello, World!"
encoded = text.encode()
print(encoded)
# b'Hello, World!'
print(type(encoded))
# <class 'bytes'>
Specifying a different encoding
text = "café"
# UTF-8 (default)
print(text.encode('utf-8'))
# b'caf\xc3\xa9'
# Latin-1 (ISO-8859-1)
print(text.encode('latin-1'))
# b'caf\xe9'
# ASCII with replacement
print(text.encode('ascii', errors='replace'))
# b'caf??'
Handling encoding errors
text = "Hello 🐍"
# strict (default) - raises an exception
try:
text.encode('ascii', errors='strict')
except UnicodeEncodeError as e:
print(f"strict: {e}")
# ignore - skip characters that can't be encoded
print(text.encode('ascii', errors='ignore'))
# b'Hello '
# replace - substitute with ?
print(text.encode('ascii', errors='replace'))
# b'Hello ?'
# backslashreplace - use \xNN notation
print(text.encode('ascii', errors='backslashreplace'))
# b'Hello \\U0001f40d'
# xmlcharrefreplace - use XML entity notation
print(text.encode('ascii', errors='xmlcharrefreplace'))
# b'Hello 🔥'
Working with files
# Writing with specific encoding
text = "Hello, 世界!"
with open("example.txt", "w", encoding="utf-8") as f:
f.write(text)
# Reading with specific encoding
with open("example.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
# Hello, 世界!
Encoding for network requests
import json
data = {"message": "Hello 🌍"}
payload = json.dumps(data).encode('utf-8')
print(payload)
# b'{"message": "Hello \\xf0\\x9f\\x8c\\x8d"}'
# Decode back
decoded = json.loads(payload.decode('utf-8'))
print(decoded)
# {'message': 'Hello 🌍'}
Common Patterns
JSON over HTTP
import urllib.request
import json
data = {"query": "Python encode"}
json_data = json.dumps(data).encode('utf-8')
req = urllib.request.Request(
"https://api.example.com/search",
data=json_data,
headers={"Content-Type": "application/json"}
)
Database storage
# Storing Unicode in a database that requires bytes
text = "日本語"
byte_data = text.encode('utf-8')
# Store byte_data in a BLOB column
Password handling
# Encoding passwords for hashing
password = "my_secure_password"
encoded_password = password.encode('utf-8')
import hashlib
hashed = hashlib.sha256(encoded_password).hexdigest()
Encoding Reference
| Encoding | Use Case |
|---|---|
utf-8 | Default, supports all Unicode characters |
latin-1 | Western European languages |
ascii | Basic English characters only |
cp1252 | Windows Western encoding |
shift_jis | Japanese |
gb2312 | Simplified Chinese |
See Also
- bytes::bytes — create bytes objects directly
- built-in::chr — convert Unicode code point to character
- built-in::ord — convert character to Unicode code point