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

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


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


The str.isalpha() function works. ie.

if my_string.isalpha():    print('it is letters')


For people finding this question via Google who might want to know if a string contains only a subset of all letters, I recommend using regexes:

import redef only_letters(tested_string):    match = re.match("^[ABCDEFGHJKLM]*$", tested_string)    return match is not None