Description: To count a special characters in a string in python, we can use a string method “Regular expression”. In this ‘re’ special characters can be defined all the non-alphanumeric characters in the string.
Using Regular Expression:
import re
def count_special_characters(s):
special_characters_pattern = r'[^a-zA-Z0-9\s]’
special_characters = re.findall(special_character_pattern, s)
return len(special_characters)
input_string = “Hi, hello, Welcome! to @1year”
count = count_special_characters(input_string)
print(“Number of special characters:”, count)
Output:
Number of special characters: 4