Python Practice › Loop Programs › Program 85
Count special characters in a file
Write a Python program to count the special characters in a file.
Input
file.txt: "student@gmail.com" / "##comment"
Output
4
Approach
- Count characters that are not letters, digits or whitespace.
Solution
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.