Handling encoding issues with Unicode normalisation in Python

When reading and writing from various systems, it is not uncommon to encounter encoding issues when the systems have different locales. In this post I show several options for handling such issues.

Example

Say you have a field containing names and there's a Czech name "Mořic" containing an r with caron, which you have to export to a csv with Windows-12521 encoding. This will fail:

>>>example='Mořic'>>>example.encode('WINDOWS-1252')UnicodeEncodeError:'charmap'codeccan't encode character '\u0159' in position 2: character maps to <undefined>

Unfortunately, Windows-1252 does not support this character and thus an exception is raised, so we need a way to handle such encoding issues.

Encoding options

Since Python 3.32, the str type is represented in Unicode. Unicode characters have no representation in bytes; this is what character encoding does - a mapping from Unicode characters to bytes. Each encoding handles the mapping differently, and not all encodings supports all Unicode characters, possibly resulting in issues when converting from one encoding to the other. Only the UTF family supports all Unicode characters. The most commonly used encoding is UTF-8, so stick with that whenever possible.

With str.encode you have several error handling options. The default signature is str.encode(encoding="utf-8", errors="strict"). Given the example "Mořic", the error options are:

To understand Unicode normal forms, we need a bit of background information first.

Unicode and composed characters

In Unicode, characters are mapped to so-called code points. Every character in the Unicode universe3 is expressed by a code point written as U+ and four hexadecimal digits; e.g. U+0061 represents lowercase "a".

The Unicode standard provides two ways for specifying composed characters:

Decomposed: as a sequence of combining characters

Precomposed: as a single combined character

For example, the character "ã" (lowercase a with tilde) in decomposed form is given as U+0061 (a) U+0303 (˜), or in precomposed form as U+00E3 (ã).

Composition and Decomposition

Composition is the process of combining multiple characters to form a single character, typically a base character and one or more marks4. Decomposition is the reverse; splitting a composed character into multiple characters.

Before diving into normalisation, let's define a function for printing the Unicode code points for each character in a string:

Canonical and Compatibility Equivalence

A problem arises when characters have multiple representations. For example the Ångström symbol Å (one Ångström unit equals one ten-billionth of a meter) can be represented in three ways:

U+212B
U+00C5
U+0041 U+030A

How can we determine if strings are equal when their decomposed forms are different? Unicode equivalence is defined in two ways:

Canonical equivalence

Compatibility equivalence

When a character from different code points has the same appearance and meaning, it is considered canonically equivalent. For example all three representations of the Ångström example above have the same appearance and meaning, and are thus canonically equivalent.

Compatibility equivalence is defined as a sequence of code points which only have the same meaning, but are not equal visually. For example fractions are considered compatible equivalent: ¼ (U+00BC) and 1⁄4 (U+0031 U+2044 U+0034) do not have the same visual appearance, but do have the same meaning and are thus compatibility equivalent.

Compatibility equivalence is considered a weaker equivalence form and a subset of canonical equivalence. When a character is canonically equivalent, it is also compatibility equivalent, but not vice versa.

Applying Unicode normalisation forms

Now, with this background information, we can get to the Unicode normal forms. Given the example "Mořic" at the start, we can apply normalisation before encoding this string with Windows-1252:

>>>importunicodedata>>>>>>defunicodes(string):>>>return' '.join('U+{:04X}'.format(ord(c))forcinstring)>>>>>>example="Mořic">>>>>>print(unicodes(example))U+004DU+006FU+0159U+0069U+0063# 5 Unicode code points, so the ř is given in precomposed form>>>example.encode("WINDOWS-1252")UnicodeEncodeError:'charmap'codeccantencodecharacter'\u0159'inposition2:charactermapsto<undefined># Windows-1252 cannot encode U+0159 (ř)>>>nfd_example=unicodedata.normalize("NFD",example)>>>print(unicodes(nfd_example))U+004DU+006FU+0072U+030CU+0069U+0063# 6 Unicode code points, so the ř is given in decomposed form>>>print(nfd_example)Mořic# Python shell with UTF-8 encoding still displays the r with caret>>>nfd_example.encode("WINDOWS-1252")UnicodeEncodeError:'charmap'codeccantencodecharacter'\u030c'inposition3:charactermapsto<undefined># Windows-1252 can now encode U+0072 (r), but not U+030C (ˇ)>>>print(nfd_example.encode('WINDOWS-1252','ignore'))Moric# Successfully encoded Windows-1252 and ignored U+030C (ˇ)

That's it! With unicodedata.normalize("NFD", "Mořic").encode('WINDOWS-1252', 'ignore') we can normalise first and then encode Windows-1252, ignoring the unknown characters for Windows-1252, resulting in Moric. I like this alternative, usually people are okay with this since it doesn't mingle the data too much and keeps it readable.

More precisely, the "Unicode universe" is the Unicode Character Database (UCD), which contains all Unicode characters and its properties and metadata. ↩

Unicode categorises characters. Each category is denoted by an abbreviation of two letters, first an uppercase and second a lowercase letter. The uppercase letters shows the major category, the lowercase the minor category. The major category for marks is "M". ↩