Specify encoding="utf-8" explicitly whenever opening files (open("file.txt", "w", encoding="utf-8")) or encoding strings to bytes (text.encode("utf-8")), and ensure your terminal/environment uses UTF-8 (PYTHONUTF8=1 or sys.stdout.reconfigure(encoding="utf-8")) when printing non-ASCII characters.
Basic Example
text = "Cafe — résumé — پاکستان — 🚀"
# WRONG: Explicitly using 'ascii' (or relying on a legacy ASCII locale) raises UnicodeEncodeError
# text.encode("ascii")
# -> UnicodeEncodeError: 'ascii' codec can't encode character '\u2014' in position 5: ordinal not in range(128)
# 1. FIX for writing files: Always pass encoding="utf-8"
with open("output.txt", "w", encoding="utf-8") as file:
file.write(text + "\n")
# 2. FIX for converting str to bytes: Encode with UTF-8
raw_bytes = text.encode("utf-8")
print(raw_bytes.decode("utf-8"))
# 3. FIX when ASCII output is strictly required: Use an error handler ('ignore', 'replace', 'xmlcharrefreplace')
ascii_safe = text.encode("ascii", errors="replace").decode("ascii")
print(ascii_safe) # Output: "Cafe ? r?sum? ? ??????? ?"
Key Details & Common Scenarios
- Why
UnicodeEncodeError: 'ascii' codec...happens: Python 3 stores strings (str) as Unicode code points, while files, sockets, and terminals operate on raw bytes. Whenever Python converts astrcontaining characters outside the 0–127 ASCII range (such as accented letters, em-dashes, curly quotes, Arabic/Urdu/CJK scripts, or emojis) using the'ascii'codec, any code point $\ge 128$ fails immediately unless encoded with a full Unicode codec like UTF-8. - 1. File I/O without
encoding="utf-8": On systems or Docker containers configured with the minimalC/POSIXlocale,open("file.txt", "w")defaults to'ascii'instead of UTF-8 (orcp1252on Windows). Always passencoding="utf-8"toopen(),Path.write_text(..., encoding="utf-8"), anddf.to_csv(..., encoding="utf-8"). - 2. Printing to
stdout/ redirected pipes in cron jobs or Docker (LANG=C): When stdout is piped (python script.py > out.txt) or run inside minimal containers whereLANG=C,sys.stdout.encodingcan fall back to'ascii'. Fix this without changingprint()calls by:- Setting the environment variable
PYTHONUTF8=1(orLC_ALL=C.UTF-8) before running Python. - Reconfiguring
stdout/stderrat the top of your script (Python 3.7+):import sys sys.stdout.reconfigure(encoding="utf-8") sys.stderr.reconfigure(encoding="utf-8")
- Setting the environment variable
- 3. URLs and HTTP headers (
urllib.parse.quote): Passing non-ASCII characters directly intourllib.request.urlopen("https://example.com/café")triggers an'ascii'encode error because HTTP request lines require ASCII. Percent-encode the path/query withurllib.parse.quote("café")first. - 4. Transliterating accented Latin text to plain ASCII (
unicodedata.normalize): If an external legacy system genuinely accepts only ASCII and you want"résumé"to become"resume"instead of"r?sum?", strip diacritics via NFKD normalization before encoding:import unicodedata normalized = unicodedata.normalize("NFKD", "résumé").encode("ascii", "ignore").decode("ascii") print(normalized) # Output: "resume"
Encoding & Error-Handling Strategy Reference
| Scenario / Requirement | Recommended Fix | Result on "café 🚀" |
Best Used When |
|---|---|---|---|
| Preserve all Unicode text (Standard) | open(p, "w", encoding="utf-8") / s.encode("utf-8") |
"café 🚀" (lossless) |
Writing files, APIs, databases, and logs in modern Python. |
Fix print() in Docker / cron / pipes |
PYTHONUTF8=1 or sys.stdout.reconfigure(encoding="utf-8") |
Prints "café 🚀" cleanly |
Subprocesses, CI runners, or Linux containers with LANG=C. |
| Strip non-ASCII characters silently | s.encode("ascii", errors="ignore").decode("ascii") |
"caf " |
Sanitizing identifiers where non-ASCII symbols should be dropped. |
Replace non-ASCII with ? |
s.encode("ascii", errors="replace").decode("ascii") |
"caf? ?" |
Legacy ASCII-only logs where character positions must remain visible. |
| Convert accents to closest ASCII letters | unicodedata.normalize("NFKD", s).encode("ascii", "ignore") |
"cafe " |
Generating ASCII filenames, slugs, or legacy database fields from Latin text. |
You must log in or register to comment.
