Skip to content

S2Q2 · Count Digits in Text

⚡ Quick Reference

Type: Full I/O problem

Core idea: Read n lines, count every character that satisfies ch.isdigit().

n = int(input())
count = 0
for _ in range(n):
    count += sum(1 for ch in input() if ch.isdigit())
print(count)

Key rules: - Count digits 0-9 only, across all lines combined - str.isdigit() is the cleanest check - Print a single integer at the end


Problem Statement

Problem

Read n (the number of lines), then n lines of text. Print the total count of numeric digit characters (0-9) present across all lines.

Examples:

Input
3
hello 123
world 45
no digits here
Output
5
Input
2
000
999
Output
6
Input
1
abc
Output
0

Understanding the problem

Walk through the first example character by character:

Line Content Digits found
1 hello 123 1, 2, 3
2 world 45 4, 5
3 no digits here (none)

Total: 3 + 2 + 0 = 5

isdigit() vs checking '0' <= ch <= '9'

Both work for plain ASCII digits, but str.isdigit() is more readable and idiomatic. Note that str.isdigit() also returns True for some Unicode digit characters (like superscripts), but for OPPE inputs with standard ASCII text this makes no practical difference.


Solution approaches

n = int(input())
count = 0
for _ in range(n):
    line = input()
    for ch in line:
        if ch.isdigit():   # True for '0' through '9'
            count += 1
print(count)
n = int(input())
text = [input() for _ in range(n)]
print(sum(ch.isdigit() for line in text for ch in line))
n = int(input())
lines = [input() for _ in range(n)]
digit_count = lambda lines: sum(1 for line in lines for ch in line if ch.isdigit())
print(digit_count(lines))

Key takeaways

01

str.isdigit() for character classification

Python's string methods let you classify characters without manual range checks. ch.isdigit() is cleaner than '0' <= ch <= '9' and signals intent clearly.

02

Flattening nested iteration with a generator

sum(ch.isdigit() for line in text for ch in line) uses a nested generator expression to iterate all characters across all lines in one pass. bool values are treated as 0/1 by sum(), so no explicit if is needed.

03

Running total vs. collect-then-count

For large inputs, updating a running count inside the loop uses O(1) memory. The list comprehension approach stores all lines first -- both are fine for OPPE inputs, but the running total is worth knowing for general use.