Home / Python / Reference / String methods

Python string encode() method

Turn text into bytes.

Syntax

str.encode(encoding="utf-8")

Files and networks store bytes; text has to be encoded. UTF-8 is the standard. bytes.decode() turns bytes back into text.

Parameters

encodingusually "utf-8"

Return value

bytes

Example

Code

b = "café".encode("utf-8")
print(b, len("café"), len(b))
print(b.decode("utf-8"))

Output

b'caf\xc3\xa9' 4 5
café

Related

Learn it step by step in the free lesson Files, with exercises that check your answers.