UnicodeEncodeError is raised when Python cannot encode a Unicode string into a specified byte encoding. The most common case is trying to write a string containing non-ASCII characters using an ASCII or Latin-1 encoding.
Why it happens
- •Writing a string with accented or non-Latin characters to a file opened with encoding='ascii'.
- •Sending Unicode text over a byte stream that expects ASCII.
- •The terminal or environment has a limited encoding (e.g. CP437 on Windows).
- •Using str.encode('ascii') on a string that contains characters outside ASCII range.
Examples
Code that triggers the error
text = "Café"
with open("output.txt", "w", encoding="ascii") as f:
f.write(text)Error output
UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 3: ordinal not in range(128)
How to fix it
Always specify encoding='utf-8' when opening files for writing. Use errors='replace' or errors='ignore' as a last resort when you cannot control the encoding. Set the PYTHONIOENCODING environment variable to utf-8 for terminal output issues.
Fixed code
text = "Café"
with open("output.txt", "w", encoding="utf-8") as f:
f.write(text)Related errors
Ready to practice your English at work?
Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.
Try Lingua-e for free