Sub topic 13
Code Points Versus Visible Characters
This chapter assumes you can index and slice strings, call len(), and read a simple try/except block. Here you will see what Python's "character" means and why it sometimes differs from what a reader sees on screen.
What an index counts
A Python string is a sequence of Unicode code points. A code point is a number that Unicode assigns to a letter, digit, symbol, or mark. Indexing, slicing, and len() all count code points. They do not count the shapes a reader sees.
Most of the time the two match. The letter P is one code point and one visible character. They diverge when a visible character is built from several code points.
An accent stored as a separate code point
Unicode can store é in two ways:
- As one code point, U+00E9, called "composed".
- As the letter
efollowed by U+0301, the combining acute accent, called "decomposed".
Both render as é. Here is the decomposed form:
s = "cafe\u0301"
print(len(s))
print(s[3])
print(ascii(s[4]))
print(s[:4])The output is:
5
e
'\u0301'
cafeThe word looks like four characters, but len(s) is 5. Index 3 is a plain e, and index 4 is the accent alone. The slice s[:4] stops before the accent, so it returns cafe with no accent. The slice cut a visible character in half and raised no error.
Comparing and normalizing
Because the two forms use different code points, Python does not treat them as equal. The standard library module unicodedata can convert between them. normalize("NFC", text) composes code points where possible.
import unicodedata
composed = "caf\u00e9"
decomposed = "cafe\u0301"
print(composed == decomposed)
print(len(composed), len(decomposed))
normalized = unicodedata.normalize("NFC", decomposed)
print(normalized == composed)
print(len(normalized))
print(normalized[:4])The output is:
False
4 5
True
4
caféAfter normalization, the string has four code points, so [:4] keeps the accent.
Other multi-code-point characters
Some emoji combine several code points. A thumbs-up with a skin tone is a base emoji followed by a modifier:
thumb = "\U0001F44D\U0001F3FD"
print(len(thumb))
print(thumb[0] == "\U0001F44D")
print(thumb[:1] == "\U0001F44D")The first line prints 2. The next two print True. Slicing thumb[:1] returns only the base emoji, which shows as a thumbs-up without the skin tone. Flags, and emoji joined by zero-width joiners such as family groups, behave the same way. Each one is a single symbol to the reader but several code points to Python.
Reversing is a related risk. A reversed string puts the combining accent before its letter, so the accent attaches to the wrong character or to nothing.
What to do about it
Python's standard library has no function that splits text into visible characters. A visible character is formally called a grapheme cluster. Your choices depend on the task:
| Situation | Approach |
|---|---|
| Input is ASCII or known to be composed | Plain indexing and slicing are fine |
| Comparing user text | Normalize both sides with `unicodedata.normalize` first |
| Truncating or reversing text shown to people | Use a grapheme-aware library such as the third-party `regex` module with `\X` |
| Working with bytes, such as files or network data | Encode first. Byte offsets differ from code point offsets |
Exercise
Let s = "e\u0301". What does len(s) return, and what is the problem with s[::-1]?
Show answer
len(s) returns 2, because the string holds the letter e and a combining accent. The reversed string is the accent followed by e. The accent now comes before its letter, so it no longer combines with the e. It attaches to whatever precedes it, or displays alone.