How to Fix Python UnicodeEncodeError
In this tutorial, you'll learn about How to Fix Python UnicodeEncodeError. We cover key concepts, practical examples, and best practices.
The Problem
You run a Python script and get UnicodeEncodeError: 'ascii' codec can't encode character '\u2019' in position 0: ordinal not in range(128). Python is trying to encode a Unicode character using ASCII, which only supports 128 characters. This commonly happens when printing Unicode text to the terminal, writing to a file without specifying encoding, or sending data over a network socket that expects ASCII.
Quick Fix
1. Set the UTF-8 locale in your shell
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
Add these to ~/.bashrc or ~/.zshrc:
echo 'export LC_ALL=en_US.UTF-8' >> ~/.bashrc
echo 'export LANG=en_US.UTF-8' >> ~/.bashrc
source ~/.bashrc
2. Set the Python IO encoding environment variable
export PYTHONIOENCODING=utf-8
This forces Python's stdin/stdout/stderr to use UTF-8 encoding. Add it to your shell profile for a permanent fix.
3. Encode and decode explicitly in code
text = "Hello, world \u2014 with em dash"
# Explicitly encode to UTF-8
bytes_data = text.encode('utf-8')
# Decode back
decoded = bytes_data.decode('utf-8')
4. Set the default encoding in your script (Python 3.7+)
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
5. Open files with explicit encoding
with open('output.txt', 'w', encoding='utf-8') as f:
f.write("Unicode text: \u00e9\u00e0\u00fc")
with open('output.txt', 'r', encoding='utf-8') as f:
content = f.read()
6. Handle errors with strategies
text = "Unicode: \u2019 and \u00e9"
# Skip characters that can't be encoded
safe = text.encode('ascii', errors='ignore')
print(safe) # b'Unicode: and '
# Replace with ?
safe = text.encode('ascii', errors='replace')
print(safe) # b'Unicode: ? and ?'
# Use XML character references
safe = text.encode('ascii', errors='xmlcharrefreplace')
print(safe) # b'Unicode: ’ and é'
7. Detect the problematic character
import unicodedata
text = "Problematic: \u2019"
for i, char in enumerate(text):
try:
char.encode('ascii')
except UnicodeEncodeError:
print(f"Position {i}: U+{ord(char):04X} ({unicodedata.name(char)})")
Common Causes
| Cause | Error Context | Fix |
|---|---|---|
| Missing locale on server | LC_ALL: cannot change locale |
locale-gen en_US.UTF-8 |
| File opened without encoding | UnicodeEncodeError on write |
Add encoding='utf-8' to open() |
| Redirecting output | print() in a pipeline |
Set PYTHONIOENCODING=utf-8 |
| Network data not decoded | Sending bytes over socket | Call .decode('utf-8') explicitly |
| Python 2 code on Python 3 | Unicode strings vs bytes | Use from __future__ import unicode_literals |
Verify Your Python Environment
python3 --version
# Python 3.10.12
pip list | grep requests
# requests 2.31.0
Check your Python version and installed packages before debugging. Many errors are caused by version mismatches between development and production environments. Using a virtual environment with pinned dependencies prevents these surprises.
Prevention
- Always specify
encoding='utf-8'when opening files in Python - Set
LC_ALL=en_US.UTF-8on Linux servers during initial setup - Use Python 3 (which defaults to UTF-8 in most configurations) over Python 2
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro