Count Special Characters
Count special characters but exclude whitespace with Python. Students combine two negated tests and distinguish punctuation from letters, digits, and spaces.
1# Take string input2s = input("Enter a string: ")34# Count special characters5count = 06for char in s:7 if not char.isalnum() and not char.isspace():8 count += 1910print(f"Special characters: {count}")
Output
Enter a string: Hello@World! Special characters: 2
In this one
- Negate character predicates
- Exclude all whitespace
- Define a special-character rule
How it works
- 1
Test each character for alphanumeric status.
- 2
Also require it not to be whitespace.
- 3
Increment only when both exclusions hold.
Edge cases
Do spaces count?
Do spaces count?
No. isspace excludes them.
Does @ count?
Does @ count?
Yes. It is neither alphanumeric nor whitespace.
What's going on
A character qualifies when it is neither alphanumeric nor whitespace. Both conditions must hold, so spaces and tabs are deliberately excluded.
For a1@!, only @ and ! count. This is a code-defined category, not a universal definition of special characters. The loop uses Unicode-aware tests, so some non-ASCII letters and numbers remain alphanumeric rather than counting as special.
Do spaces count? No. isspace excludes them.
Does @ count? Yes. It is neither alphanumeric nor whitespace.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which connection joins the exclusions?
Pick an answer to check it.
Question 2
Do spaces count?
Pick an answer to check it.
Questions people ask
Do spaces count?
No. isspace excludes them.
Does @ count?
Yes. It is neither alphanumeric nor whitespace.
Which connection joins the exclusions?
and.
๐Related Content
- ๐
Phase 5 - Learn Concepts
Review Phase 5 concepts and explanations
- ๐
Phase 5 - Quiz
Test your Phase 5 understanding with quiz questions
- ๐ป
Phase 5 - All Practice Problems
Explore all practice problems for Phase 5
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum