Understanding ord() and chr()
Computers don’t “understand” letters. They only understand numbers (specifically, binary).
The ASCII table is divided into three main sections:
Knowing these ranges helps when writing logic for data validation or “shifting” ciphers:
| Range | Character Type |
|---|---|
| 48–57 | Digits (0–9) |
| 65–90 | Uppercase (A–Z) |
| 97–122 | Lowercase (a–z) |
| 32 | Space |
Pro Tip: Note that ‘A’ (65) and ‘a’ (97) are exactly 32 apart. This is why bitwise operations can easily toggle case!
ord() FunctionThe ord() function (short for ordinal) takes a single character and returns its integer ASCII/Unicode value.
chr() FunctionThe chr() function is the inverse. It takes an integer and returns the corresponding character.
Think of them as two sides of the same coin. For any character c:
\[chr(ord(c)) = c\]
And for any valid integer i:
\[ord(chr(i)) = i\]
While ASCII stops at 127, modern Python uses Unicode (UTF-8).
ord(char) \(\rightarrow\) Integer.chr(int) \(\rightarrow\) Character.