Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Count Special Characters

Count special characters but exclude whitespace with Python. Students combine two negated tests and distinguish punctuation from letters, digits, and spaces.

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

In this one

  • Negate character predicates
  • Exclude all whitespace
  • Define a special-character rule

How it works

  1. 1

    Test each character for alphanumeric status.

  2. 2

    Also require it not to be whitespace.

  3. 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.