To check if a character is a letter in Python, use the isalpha() function.
To check if a string only contains letters in Python, you can use the string isalpha() function.
a = "h"
b = "b"
c = "1"
print(a.isalpha())
print(b.isalpha())
print(c.isalpha())
#Output:
True
True
False
When working with strings in Python, the ability to check these strings for certain conditions is very valuable.
One such case is if you want to check if a character is a letter or not.
To check if a character is a letter, we can use the string isalpha() function.
isalpha() returns True if all characters of a string are letters.
Below is an example showing you how to check if a character is a letter in Python with isalpha().
a = "h"
b = "b"
c = "1"
print(a.isalpha())
print(b.isalpha())
print(c.isalpha())
#Output:
True
True
False
Using isalpha() to Check if String Only Contains Letters
As mentioned above, we can use isalpha() to check if all characters of a string are letters.
Therefore, if we have a string of multiple characters and want to check if all of the characters are letters, we can use isalpha() to check if a string only contains letters.
Below is an example of how you can use isalpha() to check if a string only contains letters in Python.
a = "hello1"
b = "bye"
c = "123"
print(a.isalpha())
print(b.isalpha())
print(c.isalpha())
#Output:
False
True
False
Hopefully this article has been useful for you to check if a character is a letter.