Python Glossary Русский

all Python 3Byte sequencesfunction

bytes.decode

bytes — encoding

Decode the bytes to a str using an encoding (UTF-8 by default).

Syntax

b.decode(...)

The default errors='strict' turns any byte that does not fit the encoding into UnicodeDecodeError; 'replace' and 'ignore' silence it but corrupt the text in the process. latin-1 never fails because it maps all 256 byte values, so an encoding that "finally stopped erroring" is usually producing garbage rather than the right characters. Data arriving in chunks breaks as well when a split lands mid-character — that case calls for an incremental decoder instead.

Examples

print(b'hi'.decode())   # → hi
print(b'\xd0\xbf\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82'.decode('utf-8'))   # → привет
print(b'caf\xe9'.decode('latin-1'))   # → café
print(b'\xff'.decode('utf-8'))   # → UnicodeDecodeError
print(b'a\xffb'.decode('utf-8', errors='ignore'))   # → ab
print('hi'.encode())   # → b'hi'

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy