Python Practice › File Handling Programs › Program 30
Count special characters in a file
Write a Python program to count special characters (not letters, digits or whitespace) in a file.
Output
5
Approach
- Count characters that are neither alphanumeric nor whitespace.
Solution
with open("story.txt", "w") as f: f.write("Email: asha@sqatools.in! #python\n") with open("story.txt") as f: print(sum(1 for ch in f.read() if not ch.isalnum() and not ch.isspace()))Output
5
Line by line
Line 5
The special characters are :, @, ., ! and #.
Learn the concept
New to this topic? Read the lesson, then come back.