liveBook · Manning

Ord

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

ord() is a Python built-in function that returns the integer code point of a single character.

ord() is a Python built-in function that converts one character into its integer ordinal value. For ASCII letters and digits, that value is the character's position in the ASCII table. section 18.1.2

Inspect characters in a word

>>> word = "Dont" >>> for char in word: ... print(char, ord(char)) ... D 68 o 111 n 110 t 116 section 18.1.2

Use ord() when a program needs numeric character values. In a gematria-style encoder, map ord() across the characters of a cleaned word and sum the results: `return str(sum(map(ord, re.sub('[^A-Za-z0-9]', '', word))))`. A list comprehension or loop expresses the same steps, while map() keeps this version concise. section 18.3.1

Keep these related behaviors in mind:

  • Uppercase and lowercase characters have different ordinal values, such as `ord('D') == 68` and `ord('d') == 100`. section 18.1.2
  • chr() reverses the operation by converting an integer back into a character, so `chr(68)` returns `'D'`. section 18.1.2
  • Ordinal ranges expose contiguous ASCII groups such as `A-Z`, `a-z`, and `0-9`; `[A-Za-z0-9]` keeps those ranges separate in regular expressions. section 18.1.2
>>> ord('D')
68
>>> ord('o')
111

Use the compact REPL examples to verify ord() values directly, then compare them with chr() conversions. section 18.1.2

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Explains single-character conversion, case differences, ASCII ranges, reverse conversion, and composition with map() and sum().
Examples
Demonstrates REPL conversions, character iteration, ASCII tables, vowel translation tables, and a word-to-number function.
What it assumes
Assumes Python strings, loops, and functions while developing ASCII character knowledge from the beginning.
What you can do after
Apply ord() to inspect characters and build an ASCII word encoder with map(), regular expressions, and sum().
How it connects
Connects ord() with ASCII, Unicode, chr(), regular expressions, map(), list comprehensions, and sum().

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.