Count special characters in a file

EasyFile Handling Programs · 30 of 38

Write a Python program to count special characters (not letters, digits or whitespace) in a file.

Advertisement
Output
5

Approach

  1. Count characters that are neither alphanumeric nor whitespace.

Solution

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

Advertisement

Learn the concept

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

More file handling programs

← All 38 File Handling Programs