Python Practice › Loop Programs › Program 83
Count digits in a file
Write a Python program to count the digits in a file.
Input
file.txt: "Virat Kohli scored 100 in the last match"
Output
3
Approach
- Loop over every character of the file and count
isdigit().
Solution
with open("file.txt", "w") as f: f.write("Virat Kohli scored 100 in the last match") count = 0with open("file.txt") as f: for ch in f.read(): if ch.isdigit(): count += 1print(count)Output
3
Learn the concept
New to this topic? Read the lesson, then come back.