Python String isalpha() method returns True if all characters in the string are alphabets(letters). If not, it returns False.
Syntax
string.isalpha()
Parameters
It doesn’t take any parameters. An error will be shown if we try to pass any parameter to the method.
Return value
Returns true if the string consists only of alphabets. (Both uppercase and lowercase). It returns False if the string doesn’t contain alphabets or characters other than alphabets, like numerical or special characters. When it identifies a space, 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.
Visual Representation
Example 1: How does the String isalpha() Method work
string = "Ronaldo"
string2 = "Messi 10"
string3 = "Neymar@11"
print(string.isalpha())
print(string2.isalpha())
print(string3.isalpha())
Output
True
False
False
Example 2: Counting the space of string
string = "Cristiano Ronaldo"
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
String: Cristiano Ronaldo
Length of the string including space: 17
Length of the string just by counting alphabets: 16
Example 3: Using with conditions
string = "Ronaldo"
string2 = "Messi 10"
if(string.isalpha() == True):
print("All characters are alphabets(Uppercase and lowercase)")
else:
print("All characters are not alphabets(Uppercase and lowercase)")
if(string2.isalpha() == True):
print("All characters are alphabets(Uppercase and lowercase)")
else:
print("All characters are not alphabets(Uppercase and lowercase)")
Output
All characters are alphabets(Uppercase and lowercase)
All characters are not alphabets(Uppercase and lowercase)