Count the number of Special Characters in a string in Python
In this tutorial, you will learn how to count the number of special characters in a string in Python programming language.
In my previous article we have learned: How to check if a string contains a Special Character or Not in Python
Special characters are those characters that have a built-in meaning in the programming language. These can be either a single character or a set of characters. Through this example, you will be able to count the number of special characters present in a string.
Here are some examples:
Code$Speedy String contains 1 Special Character/s. Code Speedy There are no Special Characters in this String.
To count the special characters we create a function count_special_character which will count the occurrence of special characters in a particular string. We create a variable special_char and initialize it to 0. This variable special_char is used as a counter, Whenever there is an occurrence of a special character this counter is incremented by one.
Python program to count the number of special characters in a String.
#Python program to count the number of
#Special Characters in a string.
def count_special_character(string):
# Declaring variable for special characters
special_char= 0
for i in range(0, len(string)):
# len(string) function to count the
# number of characters in given string.
ch = string[i]
#.isalpha() function checks whether character
#is alphabet or not.
if (string[i].isalpha()):
continue
#.isdigit() function checks whether character
#is a number or not.
elif (string[i].isdigit()):
continue
else:
special_char += 1
if special_char >= 1:
print("String contains {} Special Character/s ".format(special_char))
else:
print("There are no Special Characters in this String.")
# Driver Code
if __name__ == '__main__' :
string = "Code%^&*$Speedy"
count_special_character(string)Output
String contains 5 Special Character/s.
First, we use For loop to iterate through the characters of the string. len(string) is used to count the number of characters which will then be used in the For loop as a parameter in the range function.
There are 2 built-in methods available in python:
- isalpha(): This method is used to check if the input character is an alphabet or not.
- isdigit(): This method is used to check if the input character is a digit or not.
If these methods are true for the character then continue statement is executed and if not true then the value of special_char is incremented by 1.
Finally, if the value of special_char is more than 1 then it is displayed as an output else message ” There are no special characters in this string ” is printed.
“ch = string[i]” seems to be redundant.