Python Count Number of Special Characters in String Example

By Hardik Savani October 30, 2023 Category : Python

Hey Developer,

Here, I will show you how to work python count number of special characters in string. step by step explain how to count special characters in python string. We will use python count number of special characters in string. you will learn python string count special characters. Alright, let us dive into the details.

In this examples, i will create countSpecialCharacter() function to count number of special characters from string in python. So, without further ado, let's see simple examples: You can use these examples with python3 (Python 3) version.

Python String Count Number of Special Characters

main.py

# Function to Count Special Character in Python
def countSpecialCharacter(string): 
    
    specialChar= 0
     
    for i in range(0, len(string)):  
        
        ch = string[i]
  
        if (string[i].isalpha()):  
            continue
          
        elif (string[i].isdigit()):
            continue
              
        else: 
            specialChar += 1
              
    return specialChar
      
# Getting Count Number of Special Character
string = "Hello%^$&^Developer"
print("Total Special Characters in String:",countSpecialCharacter(string))

Output:

7

I hope it can help you...

Tags :
Shares