Sub topic 6
Removing Accents and Diacritics Safely
This chapter assumes you can read basic Python and know what NFC and NFD mean from the previous chapter. It also assumes you know that unicodedata.normalize rewrites a string without changing how it looks. Accent removal is built on NFD, so that is the one idea you need to keep in mind.
Why strip accents at all
Users type "cafe" when the document says "café". A search index that treats these as different words misses the match. Removing accents, also called accent folding, maps both spellings to one form so they compare equal.
The cost is that accents sometimes carry meaning. Spanish "año" (year) and "ano" (anus) are different words. This chapter shows how the standard technique works, where it fails, and how to limit the damage.
What a diacritic is at the code point level
A diacritic is a mark attached to a base letter. Unicode stores many accented letters in two equivalent ways:
- A precomposed code point, such as
U+00E9(é). - A base letter followed by a combining mark, such as
eplusU+0301(combining acute accent).
NFD converts every precomposed letter to the second form. Once the marks are separate characters, you can find and delete them. Look at what NFD produces for three letters:
import unicodedata
for ch in unicodedata.normalize("NFD", "\u00e9\u00f1\u1ebf"):
print(f"U+{ord(ch):04X}", unicodedata.name(ch), unicodedata.combining(ch))
# U+0065 LATIN SMALL LETTER E 0
# U+0301 COMBINING ACUTE ACCENT 230
# U+006E LATIN SMALL LETTER N 0
# U+0303 COMBINING TILDE 230
# U+0065 LATIN SMALL LETTER E 0
# U+0302 COMBINING CIRCUMFLEX ACCENT 230
# U+0301 COMBINING ACUTE ACCENT 230The Vietnamese letter ế splits into a base e and two marks. The function unicodedata.combining(ch) returns the character's canonical combining class. That is a number describing how the mark attaches to the letter. It returns 0 for ordinary characters and a nonzero value for most combining marks.
The standard recipe
The recipe has three steps: decompose, drop the marks, recompose.
import unicodedata
def strip_accents(text):
decomposed = unicodedata.normalize("NFD", text)
kept = "".join(ch for ch in decomposed if not unicodedata.combining(ch))
return unicodedata.normalize("NFC", kept)
print(strip_accents("caf\u00e9 na\u00efve")) # cafe naiveThe final NFC step matters. After you remove marks, the string may still contain other sequences that NFD split apart. Recomposing returns it to the form the rest of your pipeline expects.
The recipe works on Latin text with ordinary accents. The next sections cover where it breaks.
Letters that do not decompose
Some letters look like "a letter plus a mark" but are separate letters in Unicode. They have no decomposition, so NFD leaves them unchanged and the recipe skips them.
| Character | Name | After `strip_accents` |
|---|---|---|
| é | e with acute | e |
| ñ | n with tilde | n |
| ü | u with diaeresis | u |
| ø | o with stroke | ø (unchanged) |
| ł | l with stroke | ł (unchanged) |
| đ | d with stroke | đ (unchanged) |
| æ | ae ligature letter | æ (unchanged) |
You can see the problem with a Polish and a Danish word:
print(strip_accents("\u0141\u00f3d\u017a \u00d8resund")) # Łodz ØresundThe ó and ź were handled, but Ł and Ø remain. Your matching is now inconsistent: a user who types "Lodz" will not find "Łódź".
The fix is an explicit translation table for the letters that need it. Build it for the languages you expect and run it before or after the recipe.
import unicodedata
EXTRA = str.maketrans({
"\u00f8": "o", "\u00d8": "O", # o with stroke
"\u0142": "l", "\u0141": "L", # l with stroke
"\u0111": "d", "\u0110": "D", # d with stroke
"\u00e6": "ae", "\u00c6": "AE", # ae
"\u0153": "oe", "\u0152": "OE", # oe
})
def strip_accents_full(text):
decomposed = unicodedata.normalize("NFD", text)
kept = "".join(ch for ch in decomposed if not unicodedata.combining(ch))
return unicodedata.normalize("NFC", kept).translate(EXTRA)
print(strip_accents_full("\u0141\u00f3d\u017a \u00d8resund")) # Lodz Oresundstr.translate accepts a one-to-many mapping, so æ can become ae. The table is a policy decision. Some languages have their own conventions, such as German ü to ue, and you should pick the convention that matches how your users type.
When stripping destroys meaning
The recipe deletes every character with a nonzero combining class. In Latin text those are accents. In other scripts they can be essential parts of the word.
Devanagari uses the virama (U+094D) to join consonants into conjuncts. It has combining class 9, so the recipe removes it:
import unicodedata
def strip_accents(text):
decomposed = unicodedata.normalize("NFD", text)
kept = "".join(ch for ch in decomposed if not unicodedata.combining(ch))
return unicodedata.normalize("NFC", kept)
word = "\u0939\u093f\u0928\u094d\u0926\u0940" # Hindi "Hindi"
stripped = strip_accents(word)
print(len(word), len(stripped)) # 6 5
print("\u094d" in stripped) # FalseThe result is a different, misspelled string. Other scripts have similar problems:
- Arabic and Hebrew: vowel marks (harakat, niqqud) have nonzero combining classes. Removing them is often desirable for search, because most text is written without them. It should still be a deliberate choice.
- Vietnamese: tone marks distinguish words. Stripping them merges unrelated words, though many users type without tones, so search systems often index both forms.
- Cyrillic:
йdecomposes toиplus a breve. Removing the breve turns "й" into "и", which changes the word.
Languages where the accented letter is a separate letter of the alphabet also lose information. Swedish å, ä, and ö come after z in the alphabet and are not variants of a and o. Turkish ı and i are different letters, as are ş and s.
Most of these cases come down to one rule: only strip marks that follow a Latin base letter.
A guarded version
You can check the base letter's Unicode name. Names of Latin letters start with LATIN. The function below removes a mark only when the character before it was Latin, and it keeps everything else.
import unicodedata
def strip_latin_accents(text):
out = []
base_is_latin = False
for ch in unicodedata.normalize("NFD", text):
if unicodedata.category(ch) == "Mn":
if base_is_latin:
continue # drop the mark
out.append(ch) # keep marks on non-Latin bases
else:
base_is_latin = unicodedata.name(ch, "").startswith("LATIN")
out.append(ch)
return unicodedata.normalize("NFC", "".join(out))
print(strip_latin_accents("Caf\u00e9 \u0439")) # Cafe йThe Cyrillic й is split by NFD, its breve is kept because the base и is not Latin, and the final NFC step puts it back together. This version uses category Mn (nonspacing mark) instead of the combining class, which is a slightly more direct way to say "this is a mark".
The guard handles scripts, but it does not handle languages. A Spanish ñ still becomes n. If your data mixes languages, decide per language, or use the strategy in the next section.
Strip for matching, keep for display
The safest design avoids a one-way deletion. Keep the original text and compute an accent-free key only for comparison.
import unicodedata
def match_key(text):
text = unicodedata.normalize("NFKC", text).casefold()
text = strip_latin_accents(text)
return text
docs = ["Caf\u00e9 de Paris", "CAFE DE PARIS", "Caf\u00e9 \u00c9mile"]
query = "cafe"
hits = [d for d in docs if query in match_key(d)]
print(hits) # ['Café de Paris', 'CAFE DE PARIS', 'Café Émile']This reuses strip_latin_accents from the previous section. The displayed documents keep their accents. Only the comparison ignores them. Search engines often go one step further and index both forms, so an exact accented query can rank above an accent-free match.
Where this step belongs in a pipeline
Accent stripping depends on earlier steps and affects later ones:
- Run NFKC first so that compatibility characters such as ligatures are plain letters before you decompose.
- Case fold before or after stripping, but be consistent. Case folding some characters produces new combining marks. For example,
İ(capital I with dot above) folds toiplusU+0307. Stripping after the fold removes that stray dot, so the result is a plaini. - Strip before you tokenise and before you match against a stop word list, so that the list and the text are in the same form. If you strip the text, strip the list too.
Common errors
- Using
str.encode("ascii", "ignore"): this deletes every non-ASCII character. "Łódź" becomes "d", not "Lodz". Decompose and remove marks instead. - Stripping without NFD:
combining()only reports marks that exist as separate characters. On a precomposedé, it returns0and nothing happens. - Forgetting the final NFC: the string looks correct but contains decomposed sequences, so later comparisons against NFC text can fail.
- Applying the recipe to all scripts: this breaks Devanagari and other scripts, as shown above.
- Stripping the text but not the stop word list: a list containing "être" never matches text that was reduced to "etre".
- Stripping stored data: if you overwrite the original, you can never recover the accents. Keep a separate key.
Deciding whether to strip
Strip accents when your users will often type without them and a missed match is worse than a false match. Search over product names or place names is the usual case. Do not strip when meaning is at stake: translation, named entity recognition on text where accents mark distinct names, and any language where the accented letters are separate letters. Chapter 11 returns to these decisions by task.
Exercise
Why does strip_accents("\u00d8resund") return the text unchanged, and how would you make "Oresund" match it?
Show answer
The letter Ø (o with stroke) is a separate Unicode letter with no decomposition, so NFD does not split it into a base plus a mark and there is nothing for the filter to remove. Add a translation table, for example str.maketrans({"\u00d8": "O", "\u00f8": "o"}), and apply it with str.translate after the recipe. Do the same for both the query and the documents.
Exercise
A search system strips combining marks from every character. A Hindi user searches for "\u0939\u093f\u0928\u094d\u0926\u0940" and finds nothing. What went wrong, and what is the fix?
Show answer
Stripping every character with a nonzero combining class removes the virama U+094D, so the stored and queried strings no longer represent the real word and the index no longer lines up with the original text. The fix is to remove marks only after Latin base letters, as strip_latin_accents does, or to skip accent removal for non-Latin scripts altogether.