Skip to content
String Methods

encode()

Turn text into bytes using an encoding such as UTF-8.

str.encode(encoding='utf-8', errors='strict')

str.encode() returns an encoded version of the string as a bytes object using the specified character encoding (default is 'utf-8').

Parameters

NameDescription
encodingThe character encoding to use; UTF-8 is the default.
errorsHow to handle characters that cannot be encoded.

Returns

A bytes object.

Try it

Run it and change it
text = "café"
print(text.encode("utf-8"))

Worth knowing

  • Error handling strategies: The errors parameter controls behavior on unencodable characters: 'strict' (raises UnicodeEncodeError), 'ignore' (skips character), or 'replace' (inserts ?).

Related entries