How to Fix UnicodeEncodeError in Python
In this tutorial, you'll learn about How to Fix UnicodeEncodeError in Python. We cover key concepts, practical examples, and best practices.
Python raises UnicodeEncodeError when encoding a Unicode string to bytes using a codec that cannot represent all characters in the string.
The Wrong Way
text = "Café"
encoded = text.encode('ascii')
print(encoded)
This produces:
Traceback (most recent call last):
File "script.py", line 2, in <module>
encoded = text.encode('ascii')
UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 3: ordinal not in range(128)
The Right Way
Use UTF-8 encoding which supports all Unicode characters:
text = "Café"
encoded = text.encode('utf-8')
print(encoded)
Output:
b'Caf\xc3\xa9'
Step-by-Step Fix
1. Always use UTF-8 for encoding
text = "Café München 东京"
encoded = text.encode('utf-8')
print(encoded)
decoded = encoded.decode('utf-8')
print(decoded)
2. Use errors='replace' or 'ignore' for fallback
text = "Café"
print(text.encode('ascii', errors='replace'))
print(text.encode('ascii', errors='ignore'))
print(text.encode('ascii', errors='xmlcharrefreplace'))
Output:
b'Caf?'
b'Caf'
b'Café'
3. Handle encoding errors when writing files
with open('output.txt', 'w', encoding='utf-8') as f:
f.write("Café München 东京")
4. Set the default encoding for stdout
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
print("Café München 东京")
Prevention Tips
- Encode all text as UTF-8 by default.
- Use
errors='replace'when encoding user-generated text. - Set
PYTHONIOENCODING=utf-8in your environment for stdout/stderr. - Open all files with
encoding='utf-8'. - Avoid ASCII-only codecs unless you are sure the text is pure ASCII.
Common Mistakes with unicodeencode
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro