Python 3 reference · String Methods
Python String encode() Method
Encode the string into bytes using a text encoding such as UTF-8 (the default), for files, networks and hashing.
Python 3 Since 3.0
Syntax
str.encode(encoding='utf-8', errors='strict')
Parameters
| Parameter | Description |
|---|---|
encoding optional |
The encoding to use. Default: 'utf-8' |
errors optional |
'strict' raises on unencodable characters; 'ignore' and 'replace' don't. Default: 'strict' |
Return value
A bytes object.
Examples
data = "café".encode()
print(data, len(data))
print(data.decode())
Output
b'caf\xc3\xa9' 5 café
print("café".encode("ascii", errors="replace"))
print("café".encode("ascii", errors="ignore"))
Output
b'caf?' b'caf'
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
str.format()· Return a formatted string, filling {} placeholders with the arguments. f-strings are usually simpler.str.translate()· Return a copy where each character is mapped through a translation table, replacing or deleting characters fast.- Python Strings · tutorial
- Python File Handling · tutorial