Python Practice › Loop Programs › Program 83

Count digits in a file

EasyLoop Programs · 83 of 90

Write a Python program to count the digits in a file.

Advertisement
Input
file.txt: "Virat Kohli scored 100 in the last match"
Output
3

Approach

  1. Loop over every character of the file and count isdigit().

Solution

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

More loop programs

← All 90 Loop Programs

Leave a Comment