The isalpha()
method in Python is used to check whether a string contains only alphabetic characters. It returns True
if all the characters in the string are letters (a-z or A-Z), and there is at least one character in the string. Otherwise, it returns False
.
Here's the syntax of the isalpha()
method:
string.isalpha()
# Examples of isalpha() method
string1 = "Hello"
string2 = "Hello123"
string3 = "12345"
result1 = string1.isalpha()
result2 = string2.isalpha()
result3 = string3.isalpha()
print("String 1:", string1)
print("String 2:", string2)
print("String 3:", string3)
print("isalpha() result for String 1:", result1)
print("isalpha() result for String 2:", result2)
print("isalpha() result for String 3:", result3)
String 1: Hello
String 2: Hello123
String 3: 12345
isalpha() result for String 1: True
isalpha() result for String 2: False
isalpha() result for String 3: False
In this example, string1
contains only alphabetic characters ("Hello"), so isalpha()
returns True
. string2
contains both letters and digits, so it is not composed entirely of alphabetic characters, and thus isalpha()
returns False
. string3
contains only digits ("12345"), so it is also not composed of alphabetic characters, and isalpha()
returns False
.
The isalpha()
method is useful for checking whether a string contains only letters, which can be handy in situations where you want to perform input validation or ensure that a string consists of alphabetic characters only.