The isalpha()
method of the String
class in Python is a built-in method that checks if a specified argument includes only alphabets (A-Z and/or a-z).
string.isalpha()
The isalpha()
method takes no parameters.
isalpha()
method returns true
if all characters in the string are alphabets. Otherwise, it returns false
.
The figure below shows the different return types of the isalpha()
method for different arguments:
string = 'Maria'
string.isalpha() #returns true
string = 'Maria04'
string.isalpha() #returns false
string = 'Maria Elijah'
string.isalpha() #returns false
The following program shows how to use the isalpha()
method.
# using isalpha()# Given stringstring='_Maria'print(string.isalpha())string1 = 'Maria Elijah'count=0# Iterate the string and check for alphabets# Increment the counter if an alphabet is found# Finally print the resultfor x in string1:if (x.isalpha()) == True:count+=1print(f"The string contains {count} alphabet")
The code above first uses the isalpha()
method on the string
variable. Next, the code iterates over each character in a string, and uses the isalpha()
method to check if the current character is an alphabet or not.