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

ParameterDescription
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

Text to bytes and backTry it yourself
data = "café".encode()
print(data, len(data))
print(data.decode())

Output

b'caf\xc3\xa9' 5
café
Characters the encoding can't representTry it yourself
print("café".encode("ascii", errors="replace"))
print("café".encode("ascii", errors="ignore"))

Output

b'caf?'
b'caf'

Version history

VersionChange
Python 3.0Added