Editor

Python Program to Find the ASCII Value of a Character

Beginner · Basics

Every character a computer stores has a number code, and for English letters, digits and common symbols that code is the ASCII value: "A" is 65, "a" is 97 and "0" is 48. This program finds the code of a character with the built-in ord function and turns a code back into a character with chr.

Program

ascii_value.py
ch = "A" # or: ch = input("Enter a character: ")
code = ord(ch)
print(f"The ASCII value of '{ch}' is {code}")
# chr() goes the other way, from a code to a character
print(f"The character with code {code + 1} is '{chr(code + 1)}'")
Output
The ASCII value of 'A' is 65
The character with code 66 is 'B'

How it works

  1. ord() takes one character and returns its number code.
  2. chr() does the opposite: it takes a code and returns the character, so chr(66) is "B".
  3. Capital letters run from 65 to 90 and small letters from 97 to 122, so a small letter is always 32 more than its capital.
  4. ord() needs exactly one character; giving it a longer string like "AB" raises an error.

Other ways to write it

ASCII values of every character in a word

ASCII values of every character in a word
word = "Python 3"
for ch in word:
print(f"'{ch}' -> {ord(ch)}")
Output
'P' -> 80
'y' -> 121
't' -> 116
'h' -> 104
'o' -> 111
'n' -> 110
' ' -> 32
'3' -> 51

Spaces and digits have codes too: the space is 32 and the digit 3 is 51.

Table of the capital letters

Table of the capital letters
for code in range(65, 91):
print(f"{code} {chr(code)}", end=" ")
if (code - 64) % 6 == 0:
print() # start a new row after every 6 letters
print()
Output
65 A   66 B   67 C   68 D   69 E   70 F   
71 G   72 H   73 I   74 J   75 K   76 L   
77 M   78 N   79 O   80 P   81 Q   82 R   
83 S   84 T   85 U   86 V   87 W   88 X   
89 Y   90 Z

Looping over the codes 65 to 90 and turning each into a letter with chr() prints the whole capital alphabet with its codes.

Try it yourself

Turn a small letter into its capital by subtracting 32 from its code with ord() and chr().

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises