PythonMastery
Python programs · Strings · beginner

Count uppercase, lowercase letters and digits in Python

Count the capital letters, small letters, digits, spaces and other characters in a sentence with isupper(), islower(), isdigit() and isspace().

Each character in a string can be tested with a string method: isupper(), islower(), isdigit() and isspace(). Go through the sentence one character at a time and add 1 to the right counter.

The program

python
text = input("Enter a sentence: ")

upper = lower = digits = spaces = other = 0
for ch in text:
    if ch.isupper():
        upper += 1
    elif ch.islower():
        lower += 1
    elif ch.isdigit():
        digits += 1
    elif ch.isspace():
        spaces += 1
    else:
        other += 1

print("Uppercase:", upper)
print("Lowercase:", lower)
print("Digits:   ", digits)
print("Spaces:   ", spaces)
print("Other:    ", other)
print("Total:    ", len(text))

Typed in this example: Ada Lovelace wrote the first program in 1843!. Press Run to type your own.

output
Enter a sentence: Ada Lovelace wrote the first program in 1843!
Uppercase: 2
Lowercase: 31
Digits:    4
Spaces:    7
Other:     1
Total:     45

How it works

Another way: sum()

True counts as 1 and False as 0, so sum() can count the characters that pass a test:

python
text = "Ada Lovelace wrote the first program in 1843!"

print("Uppercase:", sum(ch.isupper() for ch in text))
print("Lowercase:", sum(ch.islower() for ch in text))
print("Digits:   ", sum(ch.isdigit() for ch in text))
output
Uppercase: 2
Lowercase: 31
Digits:    4

This is shorter, but it reads the whole string once for each count. The loop above reads it only once. For a sentence the difference does not matter. To count each separate character instead of each kind, see count character frequency.

Learn the idea: Working with Strings, Loops: for, while, and the Pythonic Patterns