python-unicode-gotchas
Skill0 starsChanged 39 days agoMITView on GitHub
Use when handling Python text encoding — UnicodeDecodeError/EncodeError, mojibake, filesystem names with non-UTF-8 bytes, combining-character mismatches, case-insensitive string compare, regex \w/\d unexpected behavior, or round-tripping unknown-encoding files; covers error handlers (surrogateescape, backslashreplace), normalization (NFC/NFD/NFKC/NFKD), BOM handling, and open()'s encoding vs errors
In this repository66 other files it gives its agents.
- AGENTS.mdAGENTS.md
- postgres-locking-joinsSkill
- ai-bug-patternsSkill
- compressed-ndjson-boundariesSkill
- http-resume-integritySkill
- linux-io-latency-triageSkill
- macos-disk-space-recoverySkill
- minimal-sufficient-evidenceSkill
- modularize-large-filesSkill
- patch-reproducer-validitySkill
- prompt-cache-boundariesSkill
- proton-drive-selective-backupSkill
- transactional-outbox-deliverySkill
- conventional-commitsSkill
- git-advanced-mergingSkill
- git-bisect-forensicsSkill
- git-data-recoverySkill
- git-hooksSkill
- git-rerereSkill
- git-reset-mechanicsSkill
- git-revisions-syntaxSkill
- git-rewriting-historySkill
- git-submodulesSkill
- git-worktreesSkill
- github-ssh-keysSkill
- npm-publish-ci-pitfallsSkill
- sapling-stacked-pr-workflowSkill
- go-concurrency-patternsSkill
- go-data-idiomsSkill
- go-error-handlingSkill
- go-interfaces-embeddingSkill
- go-pprof-profilingSkill
- marketing-funnel-diagnosisSkill
- marketing-geo-experimentsSkill
- marketing-incrementalitySkill
- marketing-positioning-testsSkill
- python-descriptors-mroSkill
- python-logging-cookbookSkill
- python-scaling-regression-testsSkill
- rust-compile-time-invariantsSkill
- rust-deterministic-concurrency-testsSkill
- rust-error-identity-boundariesSkill
- rust-regex-search-contractsSkill
- rust-runtime-bug-classesSkill
- rust-tokio-actor-deliverySkill
- rust-tokio-cancellation-safetySkill
- sales-discovery-qualificationSkill
- sales-mutual-action-plansSkill
- sales-pipeline-forecast-calibrationSkill
- sales-value-negotiationSkill
- ai-triage-evaluationSkill
- container-image-patchingSkill
- dependency-artifact-integritySkill
- dnssec-sentinel-diagnosticsSkill
- iam-policy-change-replaySkill
- rbvm-applicabilitySkill
- rbvm-asset-evidenceSkill
- rbvm-guarded-remediationSkill
- rbvm-priority-decisionsSkill
- rbvm-risk-exceptionsSkill
- The first 60 shown.
The file
Files
Python Unicode Gotchas
str = code points, bytes = encoded output. Visually identical strings can differ in length (precomposed vs combining). str + bytes → TypeError; decode at input, encode at output.
Error handlers
| Handler | dec | enc | Effect |
strict (default) | ✓ | ✓ | raises UnicodeError |
ignore | ✓ | ✓ | drops offending char |
replace | ✓ | ✓ | U+FFFD / ? |
backslashreplace | ✓ | ✓ | \x80, \uXXXX |
xmlcharrefreplace | — | ✓ | &#NNN; |
namereplace | — | ✓ | \N{NAME} |
surrogateescape | ✓ | ✓ | lossless round-trip of unknown bytes |
surrogatepass | ✓ | ✓ | allows lone surrogates in UTF-8/16/32 |
surrogateescape maps bytes 0x80–0xFF ↔ U+DC80–U+DCFF. Use for read-then-write-back of files with unknown encoding.
File I/O
open(p, encoding='utf-8-sig') # strip UTF-8 BOM on read
open(p, encoding='ascii', errors='surrogateescape') # round-trip unknown bytesutf-16 auto-detects endianness + writes BOM; utf-16-le/-be skip BOM. Default encoding on Py3.15+ is UTF-8; on 3.10–3.14 it follows locale.getpreferredencoding() unless PYTHONUTF8=1.
Normalization
Four forms. Same visual character can be one code point or base + combining:
import unicodedata
s1 = 'ê' # len 1 — precomposed
s2 = 'e\N{COMBINING CIRCUMFLEX ACCENT}' # len 2 — decomposed
s1 == s2 # False
unicodedata.normalize('NFC', s1) == unicodedata.normalize('NFC', s2) # True| Form | Decomposes? | Compat map? | Use for |
| NFC | recomposed | no | storage, equality after input |
| NFD | fully split | no | searching / regex on base chars |
| NFKC | recomposed | yes (fi → fi) | loose matching, search keys |
| NFKD | fully split | yes | aggressive normalization |
Case-insensitive compare
def eq_ci(a, b):
n = unicodedata.normalize
return n('NFD', n('NFD', a).casefold()) == n('NFD', n('NFD', b).casefold())casefold() handles cases lower() misses (ß → ss, Greek final sigma). Double NFD because casefolding may introduce combining sequences.
Regex
| Pattern | \d | \w | \s |
str (default) | any Unicode digit | letters+digits+_ (Unicode) | Unicode whitespace |
bytes | [0-9] | [A-Za-z0-9_] | ASCII whitespace |
str + re.ASCII | [0-9] | [A-Za-z0-9_] | ASCII whitespace |
Thai ๕๗ matches \d+ in a str pattern but not with re.ASCII.
Pitfalls
len(s)≠ grapheme count: normalize first, or use a grapheme library.- Undecodable filenames:
os.listdir('.')can raise — usesurrogateescapeor passbytes. - UTF-8 BOM from Excel/Notepad: breaks naive
encoding='utf-8'; useutf-8-sig. - Python <3.15 on non-UTF-8 locale:
open()default is cp1252 etc. SetPYTHONUTF8=1or always passencoding=. casefold()still needs normalization:ss≠ßwithout it;fi≠fiwithout NFKC.- Lone surrogates only encode under
surrogatepass: astrholdingU+DC80errors on plain UTF-8 encode.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

