Editor

Python Program to Check if a Character Is a Letter, Digit or Symbol

Beginner · Basics

This program checks whether a character is a letter (an alphabet), a digit or a special symbol, and for letters it also says whether they are uppercase or lowercase. It tests several sample characters with Python's built-in string methods.

Program

character_type.py
characters = ["G", "k", "7", "@", " ", "#"]
# or: characters = [input("Enter a character: ")]
for ch in characters:
if ch.isalpha():
if ch.isupper():
print(f"'{ch}' is an uppercase letter")
else:
print(f"'{ch}' is a lowercase letter")
elif ch.isdigit():
print(f"'{ch}' is a digit")
elif ch == " ":
print(f"'{ch}' is a space")
else:
print(f"'{ch}' is a special symbol")
Output
'G' is an uppercase letter
'k' is a lowercase letter
'7' is a digit
'@' is a special symbol
' ' is a space
'#' is a special symbol

How it works

  1. ch.isalpha() is True for letters, and then ch.isupper() decides between uppercase and lowercase.
  2. ch.isdigit() is True for the digits 0 to 9.
  3. A space is not a letter, a digit or a visible symbol, so it gets a check of its own.
  4. Anything left over, like @ or #, is reported as a special symbol.
  5. isalpha() also accepts letters from other alphabets, such as é or Ω, which a check on the range A to Z would miss.

Another way to write it

Using ASCII codes

Using ASCII codes
for ch in ["G", "k", "7", "@"]:
code = ord(ch)
if 65 <= code <= 90:
kind = "an uppercase letter"
elif 97 <= code <= 122:
kind = "a lowercase letter"
elif 48 <= code <= 57:
kind = "a digit"
else:
kind = "a special symbol"
print(f"'{ch}' has ASCII code {code}, so it is {kind}")
Output
'G' has ASCII code 71, so it is an uppercase letter
'k' has ASCII code 107, so it is a lowercase letter
'7' has ASCII code 55, so it is a digit
'@' has ASCII code 64, so it is a special symbol

Every character has a number code: A to Z are 65 to 90, a to z are 97 to 122 and 0 to 9 are 48 to 57, so comparing ord(ch) with those ranges sorts it without any string methods. Unlike isalpha(), this only knows English letters.

Try it yourself

Add "z", "0", "%" and "é" to the list, and predict each answer before you run it.

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