Python Practice › Loop Programs › Program 9
Count letters and digits
Write a Python program that counts the letters and digits in a string.
Input
"python1234"
Output
Letters 6 Digits 4
Approach
- Use
isalpha()andisdigit()on each character.
Solution
text = "python1234"letters = digits = 0for ch in text: if ch.isalpha(): letters += 1 elif ch.isdigit(): digits += 1print("Letters", letters)print("Digits", digits)Output
Letters 6 Digits 4
Line by line
Lines 4-7
Spaces and symbols match neither test, so they are not counted.
Learn the concept
New to this topic? Read the lesson, then come back.