To check if the string contains only the alphabet, use the Python isalpha() function.
Python String isalpha()
Python String isalpha() is a built-in method to check whether the given string consists of only alphabets. In other words, we can say that it is a method of handling strings. The isalpha() function returns True if every character of the string is an alphabet and returns False otherwise.
See the following syntax.
Syntax
string.isalpha()
Arguments
It doesn’t take any parameters. There will error shown if we try to pass any parameter to the method.
Return value
The isalpha() function returns true if the string consists only of alphabets. (Both uppercase and lowercase)
Python string isalpha() function returns False if the string doesn’t contain alphabets or characters other than alphabets like numerical or special characters. When it identifies a space, then also it returns False.
Algorithm
1. Initialize the new string and variable counter to 0.
2. Traverse the given string character by character up to its length; check if the character is an alphabet.
3. If it is an alphabet, increment the counter by 1 and add it to the new string, else traverse to the next character.
4. The print value of the counter and the new string.
Example programs on isalpha() method
Write a program to show the mechanism of isalpha()
# app.py string = "HelloBoy" string2 = "Hello Boy" print("This string will return true as it contains only alphabets:") print("String=", string) print(string.isalpha()) print("This string will return false as it contains alphabets and one space:") print("String=", string2) print(string2.isalpha())
Output
➜ pyt python3 app.py This string will return true as it contains only alphabets: String= HelloBoy True This string will return false as it contains alphabets and one space: String= Hello Boy False ➜ pyt
Write a program to count the alphabets of the string.
# app.py string = "Hello World" count = 0 count1 = 0 for i in string: if(i.isalpha()) == True: count = count+1 for i in string: count1 = count1+1 print("String: ", string) print("Length of the string including space: ", count1) print("Length of the string just by counting alphabets: ", count)
Output
➜ pyt clear ➜ pyt python3 app.py String: Hello World Length of the string including space: 11 Length of the string just by counting alphabets: 10 ➜ pyt
Errors and Exceptions
- It contains no arguments; therefore, an error occurs if a parameter is passed.
- Both uppercase and lowercase alphabets return “True”.
- Space is not considered the alphabet; therefore, it returns “False”.
That’s it for this tutorial.