Sub topic 13
Code Points Versus Visible Characters
This chapter assumes you can already index and slice strings with positive and negative indexes. It also assumes you know that len() counts items in a sequence and that you can read a try/except block. Here you will learn what the unit of indexing really is, and why a slice that looks correct on screen can still cut a visible character in half.
What Python indexes
A Python str is an immutable sequence of Unicode code points. A code point is a number that Unicode assigns to one item in its character table, such as U+0065 for the letter e or U+0301 for a combining acute accent.
Indexing, slicing, len(), reversed() and iteration all work on code points. They do not work on what a reader sees as one character. Most of the time the two are the same, which is why the difference surprises people. For plain English text, one code point is one visible character.
The difference appears when one visible character is built from several code points. Unicode calls such a unit a grapheme cluster. Python's str has no built-in notion of grapheme clusters.
A word that looks four characters long
This is the example from the chapter plan. The string below is displayed as café, but it is written with a plain e followed by a combining accent:
s = "cafe\u0301"
print(len(s))
print(s[3])
print(ascii(s[4]))
print(s[:4])The output is:
5
e
'\u0301'
cafelen(s)is 5, although a reader counts four letters.s[3]is the plaine.s[4]is the accent on its own.ascii()shows it as an escape, because a lone combining mark has nothing to attach to and renders poorly.s[:4]iscafe. The slice is valid and raises no error, but the accent is gone, so the visible word changed.
Python did exactly what it promises. It indexed code points. The surprise comes from assuming that a code point and a visible character are the same thing.
Two ways to write the same visible text
Unicode often offers more than one encoding of the same visible character. The letter é can be one code point, U+00E9, which is called precomposed. It can also be two code points, e followed by U+0301, which is called decomposed.
precomposed = "caf\u00e9"
decomposed = "cafe\u0301"
print(precomposed == decomposed)
print(len(precomposed), len(decomposed))
print(precomposed[3] == decomposed[3])The output is:
False
4 5
FalseBoth strings look the same when printed, yet they are not equal, they have different lengths, and index 3 holds different content. This is a common source of bugs when data arrives from several sources. For example, macOS file names and text typed on some keyboards often come in the decomposed form.
Normalizing before you index
The standard library module unicodedata can convert strings to a consistent form. NFC composes sequences where a precomposed code point exists. NFD decomposes them.
import unicodedata
decomposed = "cafe\u0301"
composed = unicodedata.normalize("NFC", decomposed)
print(ascii(composed))
print(len(composed))
print(composed == "caf\u00e9")
print(composed[:4] == "caf\u00e9")The output is:
'caf\xe9'
4
True
TrueAfter normalization to NFC, é is a single code point, so composed[:4] keeps it. Normalization is a good first step, and you should apply it to input before comparing or indexing it. It does not solve everything, because many visible characters have no precomposed form. A letter with an unusual accent combination, an emoji with a skin tone, and a flag are all examples.
Visible characters that are always several code points
| Text | Visible characters | `len()` | Why |
|---|---|---|---|
| `"caf\u00e9"` | 4 | 4 | Precomposed `é` is one code point |
| `"cafe\u0301"` | 4 | 5 | `e` plus a combining accent |
| `"\U0001F44D\U0001F3FD"` | 1 | 2 | Thumbs-up plus a skin-tone modifier |
| `"\U0001F1EF\U0001F1F5"` | 1 | 2 | Two regional indicator letters that form a flag |
| `"\U0001F468\u200D\U0001F469\u200D\U0001F467"` | 1 | 5 | Three people joined by two zero-width joiners |
Here is what slicing does to the family emoji:
family = "\U0001F468\u200D\U0001F469\u200D\U0001F467"
print(len(family))
print(ascii(family[0]))
print(ascii(family[:3]))
print(ascii(family[::-1]))The output is:
5
'\U0001f468'
'\U0001f468\u200d\U0001f469'
'\u200d\U0001f467\u200d\U0001f469\U0001f468'family[0] is only the first person. family[:3] is a man, a joiner and a woman, which renders as a couple. The reversed string starts with a joiner and lists the people in the opposite order, so it renders as separate emoji or as a broken sequence. None of these results is an error, and each one is a different visible result from the one you meant.
Reversing is where it hurts most
The reversal idiom s[::-1] is correct for code points, and it is a common source of garbled text:
s = "cafe\u0301"
print(ascii(s[::-1]))The output is:
'\u0301efac'The accent now comes first. A combining mark attaches to the code point before it, so in the reversed string it has no base letter, or it attaches to whatever the previous text happens to be. A reader expects éfac and gets efac with a stray mark.
This also affects the palindrome check from earlier in the tutorial. text == text[::-1] compares code point sequences. It gives the wrong answer for decomposed text and for emoji sequences. Normalize the text first for a better check, and use grapheme clusters for a correct one.
Working with clusters
The third-party regex module supports the \X pattern, which matches one grapheme cluster. With it, regex.findall(r"\X", text) returns a list of visible characters. The standard re module does not support \X.
If you want to stay in the standard library, you can handle the most common case, base characters followed by combining marks, with unicodedata.combining(). It returns a non-zero number for combining marks and 0 for everything else.
import unicodedata
def clusters(text):
result = []
for ch in text:
if result and unicodedata.combining(ch):
result[-1] += ch
else:
result.append(ch)
return result
s = "cafe\u0301"
parts = clusters(s)
print(ascii(parts))
print(len(parts))
print(ascii("".join(parts[:4])))
print(ascii("".join(reversed(parts))))The output is:
['c', 'a', 'f', 'e\u0301']
4
'cafe\u0301'
'e\u0301fac'The list has four items, which matches what a reader sees. Slicing the list by position keeps each accent with its letter, and reversing the list keeps e\u0301 together.
Bytes are a different layer
Do not confuse code points with bytes. Encoding a string to bytes with encode() produces a sequence in which each item is a number from 0 to 255. Indexing a bytes object returns an int, not a one-character string.
text = "caf\u00e9"
data = text.encode("utf-8")
print(len(text))
print(len(data))
print(data)
print(data[3])The output is:
4
5
b'caf\xc3\xa9'
195In UTF-8, é takes two bytes. If you slice data[:4] you cut that character in half, and decoding the result with .decode("utf-8") raises UnicodeDecodeError. Slicing a str cannot create an invalid string this way, because Python only cuts between code points. The risk with a str is the visible-character problem described above, which does not raise an error.
The three layers
Decision criteria
Choose the approach by what your program does with the text.
- Identifiers, protocol fields, and ASCII data: plain indexing and slicing are safe. A code point is a character here.
- Comparing or looking up user text: normalize both sides with
unicodedata.normalize("NFC", ...)before comparing. Considercasefold()as well for case-insensitive matching. - Truncating text for display: do not cut at a fixed index. Cut between grapheme clusters, or the preview may end with a broken emoji or a missing accent.
- Reversing or counting what a reader sees: use grapheme clusters, not code points.
- Fixed-width storage limits: these are usually measured in bytes. Check
len(text.encode("utf-8")), and trim on code point boundaries so the result stays valid.
Common errors
- Assuming
len(s)is the number of visible characters. It counts code points. Use clusters when the visible count matters. - Comparing strings that look identical. Check with
ascii(), which shows escapes for every non-ASCII code point. Printing the string hides the difference. - Slicing at a fixed width.
s[:10]can end in the middle of a cluster. The result is valid Python, but it is wrong on screen. - Treating a combining mark as a normal letter.
unicodedata.name(ch)andunicodedata.combining(ch)show what a code point is. For"\u0301",namegivesCOMBINING ACUTE ACCENT. - Expecting
IndexError. None of these problems raise an error. Slicing across a cluster boundary is valid, and the damage appears only in the output.
Summary
Indexing and slicing in Python work on code points. For most text, a code point is one visible character, but accents, emoji modifiers, flags and joined emoji break that rule. Normalize with NFC for comparison, use ascii() to see what a string really contains, and use grapheme clusters when you cut or reverse text that people will read.
Exercise
Let s = "cafe\u0301". What do len(s), s[-1] and s[::-1][0] give, and how would you get a reversed string that still shows "éfac" without changing the data's decomposed form?
Show answer
len(s) is 5 because the string holds five code points. s[-1] is "\u0301", the lone combining accent, and s[::-1][0] is the same accent, since reversing puts it first. To reverse the visible characters, group each base letter with its combining marks first (for example with the clusters() helper above or regex.findall(r"\X", s)), reverse that list, and join it. This gives "e\u0301fac", which displays as "éfac".
Exercise
A user name is stored as "Zoe\u0308" (Zoë with a decomposed ë). You check it against "Zo\u00eb" with ==, and the result is False. Show the code that makes the comparison True and explain why it works.
Show answer
Normalize both strings to the same form before comparing: import unicodedata, then unicodedata.normalize("NFC", "Zoe\u0308") == unicodedata.normalize("NFC", "Zo\u00eb"). The first string has 4 code points and the second has 3, so == sees different sequences. NFC composes e plus U+0308 into the single code point U+00EB, so both strings become the same sequence and the comparison is True.