Skip to main content

How to Check If a String Contains Only Letters in Python

Validating text input is a frequent requirement in programming. Whether you are checking usernames, processing names, or analyzing text data, you often need to ensure a string consists solely of alphabetic characters (A-Z, a-z), without numbers, spaces, or special symbols.

This guide explains how to use Python's built-in string methods to verify if a string contains only letters.

Understanding the isalpha() Method

Python strings have a built-in method called .isalpha().

  • Returns True: If all characters in the string are letters and the string is not empty.
  • Returns False: If the string contains any non-letter characters (spaces, numbers, punctuation) or is empty.

Method 1: Basic Alphabetic Check

Use .isalpha() directly on the string to verify its content.

text_valid = "HelloWorld"
text_invalid = "Hello123"

# ✅ Correct: Check if strictly alphabetic
if text_valid.isalpha():
print(f"'{text_valid}' contains only letters.")
else:
print(f"'{text_valid}' contains other characters.")

# Checking invalid string
if text_invalid.isalpha():
print(f"'{text_invalid}' contains only letters.")
else:
print(f"'{text_invalid}' contains numbers or symbols.")

Output:

'HelloWorld' contains only letters.
'Hello123' contains numbers or symbols.
note

.isalpha() supports Unicode characters. So, "München" or "François" will return True.

Method 2: Handling Spaces and Multi-word Strings

A common point of confusion is strings with spaces. "Hello World" contains letters, but it also contains a space character. Since a space is not a letter, .isalpha() returns False.

If you want to allow spaces but ensure everything else is a letter, you must remove the spaces before checking.

text_with_space = "Hello World"

# ⛔️ Direct check fails because of the space
print(f"Direct check: {text_with_space.isalpha()}")

# ✅ Correct: Remove spaces first, then check
# We use .replace(" ", "") to strip spaces temporarily
if text_with_space.replace(" ", "").isalpha():
print(f"'{text_with_space}' contains only letters and spaces.")
else:
print(f"'{text_with_space}' contains other characters.")

Output:

Direct check: False
'Hello World' contains only letters and spaces.

Edge Case: Empty Strings

It is important to remember that an empty string "" is not considered alphabetic.

empty_str = ""

# Check empty string
is_alpha = empty_str.isalpha()

print(f"Is empty string alphabetic? {is_alpha}")

Output:

Is empty string alphabetic? False

Conclusion

To check if a string contains only letters in Python:

  1. Use string.isalpha() for strict validation (no spaces, digits, or symbols allowed).
  2. Handle Spaces: If you want to accept multi-word strings (like names), remove spaces using .replace(" ", "") before calling .isalpha().
  3. Remember Empty Strings: .isalpha() returns False for empty strings.