Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

str.encode

Encodes Unicode text as bytes in a chosen character encoding.

Version: Python 3.14; repository image, production runtime not attested

Syntax

s.encode(encoding="utf-8", errors="strict")

Encodes Unicode text as bytes in a chosen character encoding.

An encoding error handler controls how an unrepresentable character is handled. UTF-8 can require multiple bytes per character.

The defaults are UTF-8 and strict. In the example é needs the two UTF-8 bytes c3 a9. ASCII has no encoding for this character, so backslashreplace writes the four literal escape characters instead of raising an exception.

Examples

print("é".encode("utf-8").hex())
print("é".encode("ascii", errors="backslashreplace"))

Result

c3a9
b'\\xe9'

The defaults are UTF-8 and strict. In the example é needs the two UTF-8 bytes c3 a9. ASCII has no encoding for this character, so backslashreplace writes the four literal escape characters instead of raising an exception.

Sources