Count letters and digits
Write a Python program that counts the letters and digits in a string.
"python1234"
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)Letters 6 Digits 4
Line by line
Spaces and symbols match neither test, so they are not counted.
Learn the concept
New to this topic? Read the lesson, then come back.