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
'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
ch.isalpha()isTruefor letters, and thench.isupper()decides between uppercase and lowercase.ch.isdigit()isTruefor the digits 0 to 9.- A space is not a letter, a digit or a visible symbol, so it gets a check of its own.
- Anything left over, like @ or #, is reported as a special symbol.
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
'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.
Related programs
- Check if a Character Is a Vowel or Consonant
- Find the ASCII Value of a Character
- Count Letters, Digits and Spaces in a String
- Count Vowels, Consonants, Uppercase and Lowercase Letters
- Display a Welcome Message
- Find the Larger of Two Numbers
- Find the Largest of Three Numbers
- Check a Leap Year
- Check Whether a Number Is Even or Odd
- Swap Two Variables
All Python programs · CBSE class 12 practical file · Python exercises