Python Practice › Loop Programs › Program 85

Count special characters in a file

EasyLoop Programs · 85 of 90

Write a Python program to count the special characters in a file.

Advertisement
Input
file.txt: "student@gmail.com" / "##comment"
Output
4

Approach

  1. Count characters that are not letters, digits or whitespace.

Solution

Python
with open("file.txt", "w") as f:    f.write("student@gmail.com\n##comment\n") count = 0with open("file.txt") as f:    for line in f:        for ch in line:            if not ch.isalnum() and not ch.isspace():                count += 1print(count)
Output
4
Note

The file has 4 special characters: @, . and two #. The original sample answer (3) missed the dot.

Learn the concept

New to this topic? Read the lesson, then come back.

More loop programs

← All 90 Loop Programs

Leave a Comment