How can I check if a string only contains letters in Python?

user2745401 picture user2745401 · Sep 7, 2013 · Viewed 150.1k times · Source

I'm trying to check if a string only contains letters, not digits or symbols.

For example:

>>> only_letters("hello")
True
>>> only_letters("he7lo")
False

Answer

Martijn Pieters picture Martijn Pieters · Sep 7, 2013

Simple:

if string.isalpha():
    print("It's all letters")

str.isalpha() is only true if all characters in the string are letters:

Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.

Demo:

>>> 'hello'.isalpha()
True
>>> '42hello'.isalpha()
False
>>> 'hel lo'.isalpha()
False