Sub topic 2
Code Points, Encodings, and What a Character Is
What this chapter assumes
You should be comfortable with Python strings, loops, and functions. You should also know that text is stored as bytes in some encoding such as UTF-8. The previous chapter showed that two strings can look identical and still compare as unequal. This chapter explains the layers that make that possible. Later chapters build case folding, normalisation forms, and accent handling on top of them.
By the end you should be able to:
- Tell bytes, code points, and user-perceived characters apart.
- Predict what
len()returns for a string. - Recognise and repair the most common encoding errors.
- Inspect any character with the
unicodedatamodule.
Three layers hiding behind the word "character"
When people say "character" they usually mean a mark they can see on screen. A computer works with three separate layers.
- Bytes. A byte is a number from 0 to 255. Files, network packets, and databases store bytes.
- Code points. A code point is an integer that Unicode assigns to one abstract unit of text. It is written
U+followed by hexadecimal digits, such asU+0041for the capital letter A. - Grapheme clusters. A grapheme cluster is what a reader perceives as one character. It can be one code point or several.
An encoding converts between the first two layers. A separate set of rules in Unicode, called text segmentation, groups code points into grapheme clusters.
Most cleaning bugs come from mixing up two of these layers. A function that counts bytes when you wanted code points, or code points when you wanted grapheme clusters, gives wrong answers without raising any error.
Code points
Unicode assigns every unit of text a code point between U+0000 and U+10FFFF. A Python str is a sequence of code points. Indexing, slicing, and len() all work on code points, not on bytes.
Two built-in functions convert between a character and its number. ord() returns the code point and chr() does the reverse. The unicodedata module adds a name and a general category for each code point.
import unicodedata
for ch in ["A", "\u00e9", "\u00df", "\u20ac", "\U0001F600"]:
print(f"U+{ord(ch):04X}", unicodedata.name(ch), unicodedata.category(ch))This prints:
U+0041 LATIN CAPITAL LETTER A Lu
U+00E9 LATIN SMALL LETTER E WITH ACUTE Ll
U+00DF LATIN SMALL LETTER SHARP S Ll
U+20AC EURO SIGN Sc
U+1F600 GRINNING FACE SoThe category is a two-letter code. These codes become useful when you write cleaning rules, because they let you select whole classes of characters without listing them.
| Category | Meaning | Example |
|---|---|---|
| `Lu`, `Ll` | Uppercase and lowercase letter | `A`, `é` |
| `Mn` | Nonspacing mark (a combining accent) | `U+0301` |
| `Nd` | Decimal digit | `7` |
| `Zs` | Space separator | `U+0020`, `U+00A0` |
| `Cc` | Control character | `\n`, `\t` |
| `Cf` | Format character, usually invisible | `U+200B` |
Some code points are invisible, and they cause real trouble in scraped text. The next example prints every code point in a string that looks like a b c on screen.
import unicodedata
def describe(text):
for ch in text:
print(f"U+{ord(ch):04X}", unicodedata.category(ch), unicodedata.name(ch, "<unnamed>"))
describe("a\u00a0b\u200bc")This prints:
U+0061 Ll LATIN SMALL LETTER A
U+00A0 Zs NO-BREAK SPACE
U+0062 Ll LATIN SMALL LETTER B
U+200B Cf ZERO WIDTH SPACE
U+0063 Ll LATIN SMALL LETTER CThe no-break space looks like a space, but it is not U+0020, so text.split(" ") will not split on it. The zero-width space is invisible and also not whitespace according to str.isspace(). Chapter 7 returns to both. For now, the lesson is that describe() is the first tool to reach for when a string behaves strangely.
Encodings
A code point is only a number. To store or send it you need an encoding, which is a rule for turning code points into bytes. The same text produces different bytes under different encodings.
s = "caf\u00e9"
print(len(s)) # 4 code points
print(s.encode("utf-8")) # b'caf\xc3\xa9'
print(len(s.encode("utf-8"))) # 5 bytes
print(len(s.encode("utf-16-le"))) # 8 bytes
print(len(s.encode("utf-32-le"))) # 16 bytes
print(s.encode("latin-1")) # b'caf\xe9'The string has four code points in every case, but the byte counts are 5, 8, 16, and 4. The common encodings differ in these ways:
| Encoding | Bytes per code point | Notes |
|---|---|---|
| UTF-8 | 1 to 4 | Default for the web and most files. ASCII text is unchanged. |
| UTF-16 | 2 or 4 | Used inside Windows, Java, and JavaScript strings. |
| UTF-32 | 4 | Simple but wasteful. Rare on disk. |
| Latin-1 | 1 | Covers only 256 code points. Western European legacy text. |
UTF-8 uses a variable number of bytes. Code points up to U+007F take one byte, up to U+07FF take two, up to U+FFFF take three, and everything above takes four. That is why é (U+00E9) takes two bytes and the euro sign (U+20AC) takes three.
Not every encoding can represent every code point. Latin-1 has no euro sign, so encoding it fails.
print("\u20ac".encode("utf-8")) # b'\xe2\x82\xac'
try:
"\u20ac".encode("latin-1")
except UnicodeEncodeError as err:
print("cannot encode:", err.reason) # ordinal not in range(256)Decoding errors and mojibake
Decoding fails in the other direction when the bytes are not valid in the encoding you chose.
data = b"caf\xe9" # these bytes are Latin-1, not UTF-8
try:
data.decode("utf-8")
except UnicodeDecodeError as err:
print("cannot decode:", err.reason) # invalid continuation byte
print(repr(data.decode("utf-8", errors="replace"))) # 'caf\ufffd'
print(repr(data.decode("latin-1"))) # 'café'The errors="replace" option never raises. It substitutes U+FFFD, the replacement character, for each bad byte. The original byte is lost for good, so use this option only when losing data is acceptable.
The worse failure is silent. Latin-1 accepts every possible byte, so decoding UTF-8 bytes as Latin-1 never raises. It produces garbled text called mojibake.
good = "caf\u00e9"
garbled = good.encode("utf-8").decode("latin-1")
print(garbled) # café
repaired = garbled.encode("latin-1").decode("utf-8")
print(repaired == good) # TrueThe two-byte UTF-8 sequence C3 A9 was read as two separate Latin-1 characters, à and ©. If you see é, ’, or similar pairs in a dataset, the text was decoded with the wrong encoding at some earlier step. The round trip above repairs it only when no information was lost along the way.
The rule that prevents most of these bugs is to decode once, at the input boundary, and encode once, at the output boundary. Between those points, work only with str. Always name the encoding, because the default depends on the operating system and Python version.
with open("corpus.txt", encoding="utf-8") as handle:
text = handle.read()What a character is
The word "character" is ambiguous, so it helps to ask which layer you mean. Python's len() counts code points. That is rarely what a reader would count.
composed = "caf\u00e9" # é as one code point
decomposed = "cafe\u0301" # e followed by a combining acute accent
family = "\U0001F468\u200D\U0001F469\u200D\U0001F467"
flag = "\U0001F1E9\U0001F1EA"
print(len(composed), len(decomposed)) # 4 5
print(len(family)) # 5
print(len(flag)) # 2Each case shows a different effect:
- Combining marks.
écan be one code point (U+00E9) or two (eplusU+0301). Both display identically, which is the root cause of the unequal strings from the previous chapter. The two spellings are made equal by the normalisation forms in chapter 4. - Joined sequences. The family emoji is three person emoji joined by two zero-width joiners (
U+200D). Five code points render as one picture. - Paired symbols. A flag is two regional indicator letters, here D and E, that the font combines into one flag.
Counting grapheme clusters needs a rule set the standard library does not ship. The third-party regex module (install it with pip install regex) supports the \X pattern, which matches one grapheme cluster.
import regex
for text in ["caf\u00e9", "cafe\u0301", family, flag]:
print(len(text), len(regex.findall(r"\X", text)))This prints 4 4, 5 4, 5 1, and 2 1. The code point count varies, but the cluster count matches what a reader sees.
Which layer to use for which task
| Task | Layer that matters |
|---|---|
| Reading and writing files, network transfer | Bytes and encoding |
| Comparing, searching, case folding, normalising | Code points |
| Truncating text for display, cursor movement, character limits shown to users | Grapheme clusters |
| Slicing a string without splitting a character | Grapheme clusters |
Slicing is a frequent source of damage. Cutting "cafe\u0301"[:4] returns "cafe" and drops the accent, because the accent is a separate code point. For machine processing this is often acceptable. For anything shown to people, cut at grapheme boundaries.
Common errors
- Assuming one character is one byte. This holds only for ASCII. Measure byte length with
len(s.encode("utf-8"))when a limit is in bytes, such as a database column. - Relying on the default encoding. A script that works on one machine fails on another. Pass
encoding="utf-8"toopen(). - Treating
len()as a count of visible characters. It counts code points, so combining marks and emoji sequences throw it off. - Fixing mojibake by deleting symbols. Repair the decoding step instead.
- Trusting what you see. Two strings that look the same can differ in code points. Use
describe()orrepr()to check, sincerepr()shows escapes for many unusual characters.
Exercise
The string s = "nai\u0308ve" displays as "naïve". What does len(s) return, what does len(s.encode("utf-8")) return, and how many grapheme clusters does a reader see?
Show answer
len(s) is 6, because the string holds n, a, i, a combining diaeresis (U+0308), v, and e. The UTF-8 encoding is 7 bytes, because every code point is ASCII except U+0308, which takes 2 bytes (ASCII letters 5 bytes plus 2). A reader sees 5 grapheme clusters: n, a, ï, v, e.
Exercise
A CSV file read with encoding="latin-1" shows the text "données" where "données" was expected. What went wrong, and what two lines of Python recover the correct string from the variable bad?
Show answer
The file was written as UTF-8 but decoded as Latin-1, so the two-byte sequence for é was read as the two characters à and ©. Recover it with: raw = bad.encode("latin-1") and then raw.decode("utf-8"). The better fix is to open the file with encoding="utf-8" in the first place.