Count the number of alphabets in a string in Python
In this tutorial, you will learn how to count the number of alphabets in a string in Python. A string is a pre-defined class that consists of various methods for performing various tasks on strings.
Here, we are going to use some predefined functions to count the number of alphabets in a string in Python.
- isalpha() is a built-in method for string typed object we use in this tutorial
isalpha() method is a predefined built-in method for string type objects. isalpha() method returns True if all the characters are alphabets from a to z otherwise returns False.
For further reference on isalpha() method click here ->String – isalpha()
#Example of isalpha() method string="alphabtes" alphanumeric="alpha123" print(string.isalpha()) # return true print(alphanumeric.isalpha()) #return false
The output of the above code is :
From the above code, the first print statement returns true as all the characters in the string are letters.
In the second print, the statement returns false as all characters in the alphanumeric are a combination of letters and numbers.
As isalpha() method returns True if the given string contains alphabets. We can count the number of characters of a string by applying this method to every element of this string using a loop. So, we increment a count variable by 1 to count the number of characters in a given string.
Let’s have a glance over the following code:
s="[email protected]" count=0 for i in s: # i holds each character in String s for every iteration of loop if(i.isalpha()): count=count+1 # Increment Count by 1 print("Number of Characters =",count)
For the above code, the output will be as follows:
Number of Characters = 8
From the above code, given String is “[email protected]”. We have iterated by every character through the entire string. We have applied isalpha() Method for each character in the given string. If the isalpha() method returns True then the value of count will be incremented by 1 which counts the number of alphabets in a given string.
In this way, we can count the number of alphabets in a given string. For further reading on operations that can be performed on the string, click here ->Unique Characters of a String