UnicodeEncodeError
UnicodeEncodeError: 'ascii' codec can't encode character
Traceback
Traceback (most recent call last):
File "main.py", line 1, in <module>
"café".encode("ascii")
UnicodeEncodeError: 'ascii' codec can't encode characterWhat causes this error
A string contains characters that cannot be represented in the target encoding — for example, emoji or accented characters when encoding to ASCII.
How to fix it
Use UTF-8 encoding for maximum compatibility. Set encoding explicitly with `open(file, 'w', encoding='utf-8')`. Use `str.encode('utf-8', errors='replace')` when the target encoding is limited.
Code that causes this error
"café".encode("ascii")Fixed code
"café".encode("utf-8")
# or with fallback:
"café".encode("ascii", errors="replace") # b'caf?'About UnicodeEncodeError
A UnicodeEncodeError is raised when converting a string to bytes and the string contains characters that cannot be represented in the target encoding. This commonly happens when writing Unicode text to a file opened with an ASCII encoding, printing characters to a terminal that does not support the character's encoding, or encoding text for network transmission. In Python 3 the default encoding for many operations is UTF-8, but legacy systems, some Windows configurations, and older libraries may default to ASCII or other limited encodings.
The error message identifies the codec, the position of the problematic character, and the character itself. Setting the encoding explicitly (typically to 'utf-8') when opening files or encoding strings resolves most cases. For situations where data loss is acceptable, error handlers like 'replace', 'ignore', or 'xmlcharrefreplace' provide fallback behavior.
Common scenarios
Converting user input strings to numbers without validation
Unpacking iterables with an unexpected number of elements
Passing out-of-range values to mathematical functions
Processing data files with inconsistent or malformed records