Characters beyond A to Z
Python text is Unicode: é, ü and ☃ are one character each. ord gives a character's number, and chr turns a number back into a character.
- Count and index text with accented letters correctly
- Convert between characters and code points with
ordandchr - Use letter arithmetic, such as a letter's place in the alphabet, and test for plain ASCII
Real data is not limited to A–Z. Open Food Facts has products such as *Weetabix produit à base de blé complet* from the brand *Brüggen*, and customer names include José and Zoë. Python text is a sequence of Unicode characters, so é is one character to len, to indexing and to loops, exactly like e.
Every character has a number, its code point. ord("A") is 65, and chr(65) goes back to "A". The letters A–Z are 65–90 and a–z are 97–122, and anything above 127 is outside plain ASCII.
Run each example to see what it prints. Running examples doesn't count toward progress.
brand = "Brüggen" print(len(brand), brand[2]) print(ord("A"), ord("a"), ord("ü")) print(chr(233), chr(9731)) print("Zoë".upper())
Because characters are numbers, you can compute with them. The letters are consecutive, so ord(letter) - ord("A") is a capital letter's place in the alphabet, counting A as 0. Spreadsheets use this to number their columns: A is column 1, Z is 26, AA is 27, and each extra letter works like a digit in base 26.
column = "AB" number = 0 for letter in column: number = number * 26 + (ord(letter) - ord("A") + 1) print(letter, number) print(column, "is column", number)
print(ord("é")) print(ord("AB"))
When to use it: whenever text might come from anywhere. Count characters rather than letters, test whether a name is plain ASCII with ord(ch) < 128, or compute with letters. Mistakes to avoid:
- Assuming every character is A–Z.
- Passing more than one character to
ord. - Expecting two texts that look the same to be equal. An
écan also be stored asefollowed by a separate accent character, which is two characters. The concept check runs that case.
- Python text is Unicode. é, ü and ☃ each count as one character for len, indexing and loops.
ord(ch)is a character's code point, andchr(n)turns a number back into a character. Plain ASCII is below 128.- Letters are consecutive numbers, so arithmetic on
ordcan shift or number them. - Next module: lists and tuples hold many values in order, not only characters.