Editor

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

count_letters_digits_spaces.py
text = "Room 101, Block B: open 24 hours!" # or: text = input("Enter a string: ")
letters = 0
digits = 0
spaces = 0
others = 0
for ch in text:
if ch.isalpha():
letters += 1
elif ch.isdigit():
digits += 1
elif ch.isspace():
spaces += 1
else:
others += 1 # punctuation and symbols
print("String:", text)
print("Letters:", letters)
print("Digits:", digits)
print("Spaces:", spaces)
print("Other characters:", others)
print("Total characters:", len(text))
Output
String: Room 101, Block B: open 24 hours!
Letters: 19
Digits: 5
Spaces: 6
Other characters: 3
Total characters: 33

How it works

  1. ch.isalpha() is True for letters, ch.isdigit() for the digits 0 to 9, and ch.isspace() for spaces, tabs and new lines.
  2. The if/elif chain puts each character into exactly one group, so the four counts always add up to the length of the string.
  3. Anything that is not a letter, digit or space, like ,, : and !, falls through to else and counts as another character.
  4. The last line prints len(text) so you can check that the four counts add up.

Other ways to write it

Using sum()

Using sum()
text = "Room 101, Block B: open 24 hours!"
letters = sum(1 for ch in text if ch.isalpha())
digits = sum(1 for ch in text if ch.isdigit())
spaces = sum(1 for ch in text if ch.isspace())
print("Letters:", letters, "| Digits:", digits, "| Spaces:", spaces)
print("Other characters:", len(text) - letters - digits - spaces)
Output
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

Using comparisons instead of methods
text = "Room 101, Block B: open 24 hours!"
letters = digits = spaces = 0
for ch in text:
if "a" <= ch <= "z" or "A" <= ch <= "Z":
letters += 1
elif "0" <= ch <= "9":
digits += 1
elif ch == " ":
spaces += 1
print("Letters:", letters, "| Digits:", digits, "| Spaces:", spaces)
Output
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.

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