Python Program to Count Letters, Digits and Spaces in a String
Beginner · Strings
This program sorts every character of a string into four groups, letters, digits, spaces and other symbols, and counts each group. It uses the string methods isalpha(), isdigit() and isspace(), which test what kind of character something is.
Program
String: Room 101, Block B: open 24 hours! Letters: 19 Digits: 5 Spaces: 6 Other characters: 3 Total characters: 33
How it works
ch.isalpha()isTruefor letters,ch.isdigit()for the digits 0 to 9, andch.isspace()for spaces, tabs and new lines.- The
if/elifchain puts each character into exactly one group, so the four counts always add up to the length of the string. - Anything that is not a letter, digit or space, like
,,:and!, falls through toelseand counts as another character. - The last line prints
len(text)so you can check that the four counts add up.
Other ways to write it
Using sum()
Letters: 19 | Digits: 5 | Spaces: 6 Other characters: 3
Each sum() adds 1 for every character that passes its test. It is shorter, but the string is scanned once for every count.
Using comparisons instead of methods
Letters: 19 | Digits: 5 | Spaces: 6
Characters can be compared by their codes, so "a" <= ch <= "z" is true for small letters. This counts English letters only, while isalpha() also accepts letters like é and ñ.
Try it yourself
Add counters for capital and small letters using isupper() and islower().
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
- Count Vowels, Consonants, Uppercase and Lowercase Letters
- Check if a Character Is a Letter, Digit or Symbol
- Extract Numbers from a String
- Check a Palindrome String
- Reverse a String
- Generate a Random Password
- Count the Frequency of Each Character in a String
- Count the Words in a String
- Remove Punctuation from a String
All Python programs · CBSE class 12 practical file · Python exercises