runtime
30 / 250
lesson 30 Strings & Text · beginner

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.

You'll be able to
  • Count and index text with accented letters correctly
  • Convert between characters and code points with ord and chr
  • Use letter arithmetic, such as a letter's place in the alphabet, and test for plain ASCII
The idea

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.

example-1.py · Characters and their numbers
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.

example-2.py · Spreadsheet column letters to a number
column = "AB"
number = 0
for letter in column:
    number = number * 26 + (ord(letter) - ord("A") + 1)
    print(letter, number)
print(column, "is column", number)
example-3.py · ord takes one character
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 as e followed by a separate accent character, which is two characters. The concept check runs that case.
Review
  • Python text is Unicode. é, ü and ☃ each count as one character for len, indexing and loops.
  • ord(ch) is a character's code point, and chr(n) turns a number back into a character. Plain ASCII is below 128.
  • Letters are consecutive numbers, so arithmetic on ord can shift or number them.
  • Next module: lists and tuples hold many values in order, not only characters.
Practise this

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

Characters beyond A to Z — Strings & Text · Runtime