Count Special Characters

Count special characters in string.

IntermediatePhase 5 - Category 2: Character OperationsExample 7 of 10
count-special-characters.py
1# Take string input
2s = input("Enter a string: ")
3
4# Count special characters
5count = 0
6for char in s:
7 if not char.isalnum() and not char.isspace():
8 count += 1
9
10print(f"Special characters: {count}")

Output

Enter a string: Hello@World!
Special characters: 2

What's going on

Count characters that are not alphanumeric or space.

Key Concepts:

isalnum() checks alphanumeric
isspace() checks space
Count if neither