Home » Count total number of alphabets, digits and special characters using python

Count total number of alphabets, digits and special characters using python

Spring Framework Basics Video Course
Java SE 11 Programmer II [1Z0-816] Practice Tests
Oracle Java Certification
Java SE 11 Developer (Upgrade) [1Z0-817]
Java SE 11 Programmer I [1Z0-815] Practice Tests
1 Year Subscription

In this article we count the occurrences of letters, digits and special characters in a string using python

Example

We use isalpha() to check if all the characters in the text are letters, if they are a variable called letter is incremented

We use isdigit() to check if all the characters in the text are digits, if they are a variable called number is incremented

Otherwise its a special character then we increment the special variable

# Count letters numbers and Special Characters in a String
myString = input("Please Enter your String : ")
letter = number = special = 0

for i in range(len(myString)):
    if(myString[i].isalpha()):
        letter = letter + 1
    elif(myString[i].isdigit()):
        number = number + 1
    else:
        special = special + 1
        
print("\nTotal Number of letters in this String :  ", letter)
print("Total Number of numbers in this String :  ", number)
print("Total Number of Special Characters in this String :  ", special)

When you run this you will see something like this

>>> %Run countcharstring.py
Please Enter your String : This is 1 test string with 2 or more characters !!

Total Number of letters in this String :   36
Total Number of numbers in this String :   2
Total Number of Special Characters in this String :   12

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More