Every character is stored as a number. ord() gives you the number for a character, and chr() gives you the character for a number. For the letters, digits and symbols on an English keyboard, these numbers are the ASCII codes.
The program
char = input("Enter a character: ") print(f"The ASCII value of '{char}' is {ord(char)}")
Typed in this example: A. Press Run to type your own.
Enter a character: A The ASCII value of 'A' is 65
How it works
ord("A")returns 65.ord()needs exactly one character:ord("ab")raises aTypeError.- Capital and small letters have different codes. "A" is 65 and "a" is 97, so the difference is always 32.
- The digit characters have codes too. The character
"0"is 48, not 0.
print(ord("a"), ord("z"), ord("0"), ord(" ")) print(chr(65), chr(97), chr(48))
97 122 48 32 A a 0
A range of letters
The letters have codes in alphabetical order, so you can loop over the codes and turn each one back into a letter:
for code in range(ord("A"), ord("F") + 1): print(code, chr(code)) letters = "".join(chr(code) for code in range(ord("a"), ord("z") + 1)) print(letters)
65 A 66 B 67 C 68 D 69 E 70 F abcdefghijklmnopqrstuvwxyz
range(ord("A"), ord("F") + 1) is range(65, 71). The + 1 is needed because range() stops before its end value. The string module already has the alphabet ready: string.ascii_lowercase and string.ascii_uppercase.
Beyond ASCII
ASCII covers only codes 0 to 127. Python strings use Unicode, so ord() also works for any other character:
for char in ["é", "€", "ж", "あ"]: print(char, ord(char))
é 233 € 8364 ж 1078 あ 12354