Sub topic 1
Why the same text looks different to a computer
Prerequisites
You should know basic Python: strings, print, and functions. You should also know that text is stored as bytes in an encoding such as UTF-8. No prior Unicode knowledge is assumed.
Same text, different code points
Python compares strings by code points, the integer numbers that Unicode assigns to characters. The letter é can be stored as one code point (U+00E9), or as two: e (U+0065) followed by a combining acute accent (U+0301). Both render as "é", but the strings are not equal.
a = "caf\u00e9"
b = "cafe\u0301"
print(a == b) # False
print(len(a), len(b)) # 4 5Encodings turn code points into bytes
An encoding converts code points into bytes for storage or transfer. UTF-8 stores é as two bytes (C3 A9). Latin-1 stores it as one byte (E9). Decoding bytes with the wrong encoding produces garbled text, so know which encoding your data uses.
Case: lowercasing versus case folding
str.lower() is not always enough for caseless comparison. The German letter ß stays unchanged when lowercased, but casefold() maps it to "ss".
print("Stra\u00dfe".lower()) # straße
print("Stra\u00dfe".casefold()) # strasse
print("Stra\u00dfe".casefold() == "STRASSE".casefold()) # TrueUse casefold() for matching. Use lower() when you only need to display text.
Unicode normalisation: NFC and NFD
Normalisation converts equivalent strings to one standard form. NFC composes base letters and marks into single code points where possible. NFD splits them into a base letter plus combining marks.
import unicodedata
a = "caf\u00e9"
b = "cafe\u0301"
print(unicodedata.normalize("NFC", b) == a) # True
print(unicodedata.normalize("NFD", a) == b) # TrueUse NFC for storage and most comparisons. Use NFD when you need to separate marks from base letters, for example when removing accents.
Exercise
What does unicodedata.normalize("NFC", "cafe\u0301") == "caf\u00e9" return, and why?
Show answer
It returns True. NFC composes the e and the combining acute accent (U+0301) into the single code point U+00E9, so the two strings become identical.