Python String isalpha() Method: Check if String is Alphabetic
This code defines a function that uses Python's str.isalpha() method to determine if a string contains only alphabetic characters, with a demonstration on several test strings.
Python code
7 linesdef is_alphabetic(s):
return s.isalpha()
if __name__ == "__main__":
test_strings = ["Hello", "Hello123", "World!", "Python", ""]
for s in test_strings:
print(f"{s!r}: {is_alphabetic(s)}")
Output
"Hello": True
"Hello123": False
"World!": False
"Python": True
"": False
How it works
The isalpha() method returns True if every character in the string is an alphabetic character (as defined by Unicode) and the string has at least one character. It returns False for empty strings and for strings containing digits, punctuation, whitespace, or other non-letter symbols. This function is a simple wrapper around that built-in method, making the intent clear and reusable. Because it relies on the standard library, it works out-of-the-box on any Python installation.
Common mistakes
- Forgetting that spaces are not alphabetic, so 'hello world' returns False.
- Assuming isalpha() only works for ASCII letters; it also covers Unicode letters like 'é' or '中'.
- Not handling empty strings — isalpha() returns False, not an error.
- Using isalpha() to validate names with hyphens or apostrophes (they will fail).
Variations
- For ASCII-only checks, use `all(c.isalpha() for c in s)` after ensuring s is not empty.
- Use regular expression `re.fullmatch(r'[A-Za-z]+', s)` to restrict to English letters.
Real-world use cases
- Validating form inputs where only letters are allowed (e.g., names without numbers or special characters).
- Filtering text tokens in a data pipeline to keep only alphabetic words for analysis.
- Checking command-line arguments to ensure an ID or code contains only letters before lookup.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.