Python String isalpha() Method
The isalpha()
method is used to check whether all characters in a string are alphabetic (i.e., only letters).
Syntax
string.isalpha()
Parameters
No parameters.
Return Value
Returns True
if all characters in the string are alphabetic (a-z, A-Z) and the string is not empty.
Returns False
if the string contains any non-alphabetic character (like space, punctuation marks, or special symbols) or is empty.
Examples
Check if All Characters in a String are Letters
print("hello".isalpha()) # Output: True
print("123".isalpha()) # Output: False
print("hello world".isalpha()) # Output: False (contains space)
print("hello22".isalpha()) # Output: False (contains numbers)
print("hello!".isalpha()) # Output: False (contains special symbol)
print("".isalpha()) # Output: False (empty string)
Practical Usage
Let’s ask the user for first name and last name inputs, and check if all characters are letters. If both the first name and last name are valid (letters only), print the greeting. Otherwise, tell the user that the name is invalid.
first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
if first_name.isalpha() and last_name.isalpha():
print(f"Hello, {first_name} {last_name}!")
else:
print("Invalid Name")
Output:
For the first name James
and last name Bond
Hello, James Bond!
For the first name James22
and last name Bond
Invalid Name