PythonMastery

Find the ASCII value of a character in Python

Get the ASCII code of a character with ord(), turn a code back into a character with chr(), and print a range of letters with their codes.

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

python
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.

output
Enter a character: A
The ASCII value of 'A' is 65

How it works

python
print(ord("a"), ord("z"), ord("0"), ord(" "))
print(chr(65), chr(97), chr(48))
output
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:

python
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)
output
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:

python
for char in ["é", "€", "ж", "あ"]:
    print(char, ord(char))
output
é 233
€ 8364
ж 1078
あ 12354

Learn the idea: Working with Strings