Python Practice › Loop Programs › Program 9

Count letters and digits

EasyLoop Programs · 9 of 90

Write a Python program that counts the letters and digits in a string.

Advertisement
Input
"python1234"
Output
Letters 6
Digits 4

Approach

  1. Use isalpha() and isdigit() on each character.

Solution

Python
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.

More loop programs

← All 90 Loop Programs

Leave a Comment