Most text bugs come from mixing up three different things: what a person sees, what Unicode defines and what is stored as bytes.
Code points
Unicode assigns a number, called a code point, to every character: A is U+0041, é is U+00E9, the thumbs-up emoji is U+1F44D. It is a catalogue, not an encoding.
UTF-8
UTF-8 is the most common way to turn code points into bytes. It uses one to four bytes per code point. ASCII characters take one byte, so plain English text is identical to ASCII, while accented letters usually take two, many Asian characters three and emoji four.
text = "é"
print(len(text)) # 1 code point
print(len(text.encode("utf-8"))) # 2 bytes
thumbs = "👍"
print(len(thumbs), len(thumbs.encode("utf-8"))) # 1 code point, 4 bytesWhat users call a character
One visible symbol can be several code points. The letter é can be written as one code point (U+00E9) or as e followed by a combining accent (U+0301). Many emoji are sequences joined together. A user-perceived character is a grapheme cluster.
composed = "é"
decomposed = "é"
print(composed == decomposed) # False, although both look identical
print(len(composed), len(decomposed)) # 1 2Normalisation
To compare or search text correctly, convert both sides to the same normalisation form, usually NFC. Without it, two strings that look the same can differ, which breaks lookups, deduplication and security checks such as comparing usernames.
import unicodedata
a = unicodedata.normalize("NFC", "é")
print(a == "é") # TrueHabits that prevent bugs
- Decode bytes to text as early as possible, work with text inside the program and encode at the boundary. Always state the encoding explicitly.
- Use UTF-8 everywhere: files, databases, HTTP headers.
- Do not slice strings by byte or code point when cutting text for display. Use a library that understands grapheme clusters.
- Be aware that
lengthmeans different things in different languages: bytes, UTF-16 units or code points. - Case conversion and sorting depend on the language. Use locale-aware functions where it matters.
Takeaway
Think in layers: grapheme cluster for the user, code point for Unicode, bytes for storage. Name your encoding, normalise before comparing and test with accents and emoji.
Comments