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
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.
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
upper = lower = digits = spaces = other = 0sets all five counters to 0 in one line.- The
if/elifchain puts each character into exactly one group. The lastelsecatches everything left over: punctuation such as "!" and symbols such as "@". - The five counts always add up to
len(text). That is an easy way to check that no character was missed or counted twice.
Another way: sum()
True counts as 1 and False as 0, so sum() can count the characters that pass a test:
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))
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.