Python Glossary Русский

all Python 3codecsfunction

codecs.encode()

encoding and decoding

Encodes an object with a codec looked up by name. For text str.encode is enough; codecs.encode is for bytes-to-bytes and text-to-text codecs: base64, hex, zlib, rot13.

Syntax

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

For an ordinary string this is the same as str.encode, so codecs.encode('я', 'utf-8') buys nothing. What it adds is reach: str.encode accepts only text encodings and answers 'base64' with a LookupError saying it 'is not a text encoding', while codecs.encode runs any codec, including base64 and zlib over bytes. The codec decides the input type: base64 wants bytes, rot13 wants str, and the wrong one raises TypeError. The default encoding is 'utf-8', not the locale encoding.

Examples

import codecs
print(codecs.encode(b'hi', 'base64'))  # → b'aGk=\n'
print(codecs.encode('Hello', 'rot13'))  # → Uryyb
print(codecs.encode(b'hi', 'hex'))  # → b'6869'
try:
    'hi'.encode('base64')
except LookupError as e:
    print(type(e).__name__)  # → LookupError — str.encode берёт только текстовые кодировки

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy