Python Glossary Русский

all Python 3Exceptionsexception

UnicodeEncodeError

built-in exceptions

Failed to encode a string into bytes.

Syntax

raise UnicodeEncodeError

This is the mirror image of decoding: the character exists in your string, but the target encoding has no way to express it — ascii knows neither a snowman nor Cyrillic. For students it usually isn't an explicit encode() call but a plain print() into a console stuck on a legacy code page: the string itself is fine, only the output path breaks. When the data must stay recoverable, prefer errors='backslashreplace' or 'xmlcharrefreplace' over 'ignore', which silently throws characters away for good.

Examples

try:
    '\u2603'.encode('ascii')
except UnicodeEncodeError as e:
    print(type(e).__name__)   # → UnicodeEncodeError

See also

Open in the full glossarydocs.python.orgReport an inaccuracy