0
0
PythonHow-ToBeginner · 3 min read

How to Check if String is Alpha in Python: Simple Guide

In Python, you can check if a string contains only alphabetic characters using the isalpha() method. This method returns True if all characters in the string are letters and there is at least one character; otherwise, it returns False.
📐

Syntax

The isalpha() method is called on a string to check if it contains only letters.

  • string.isalpha(): Returns True if all characters in string are alphabetic and the string is not empty.
  • Returns False if the string contains any non-letter characters like digits, spaces, or punctuation.
python
string.isalpha()
💻

Example

This example shows how to use isalpha() to check different strings and print whether they are alphabetic.

python
words = ['Hello', 'Python3', '', 'DataScience', '123', 'Hello World']

for word in words:
    if word.isalpha():
        print(f"'{word}' is alphabetic.")
    else:
        print(f"'{word}' is NOT alphabetic.")
Output
'Hello' is alphabetic. 'Python3' is NOT alphabetic. '' is NOT alphabetic. 'DataScience' is alphabetic. '123' is NOT alphabetic. 'Hello World' is NOT alphabetic.
⚠️

Common Pitfalls

Some common mistakes when using isalpha() include:

  • Expecting it to return True for strings with spaces or numbers (it won't).
  • Using it on empty strings, which always return False.
  • Not realizing that accented letters or unicode letters count as alphabetic.

Here is a wrong and right way example:

python
# Wrong: expecting True for string with space
text = 'Hello World'
print(text.isalpha())  # Output: False

# Right: remove spaces before checking
text_clean = text.replace(' ', '')
print(text_clean.isalpha())  # Output: True
Output
False True
📊

Quick Reference

MethodDescriptionReturns
isalpha()Checks if all characters are letters and string is not emptyTrue or False
replace(' ', '')Removes spaces from string (useful before isalpha())New string without spaces
strip()Removes leading/trailing whitespaceNew trimmed string

Key Takeaways

Use isalpha() to check if a string contains only letters and is not empty.
Strings with spaces, digits, or punctuation return False with isalpha().
Empty strings always return False with isalpha().
Remove spaces or unwanted characters before using isalpha() if needed.
Unicode letters and accented characters count as alphabetic in isalpha().