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

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

This question is related to python string conditional-statements

The answer is


The string.isalpha() function will work for you.

See http://www.tutorialspoint.com/python/string_isalpha.htm


A pretty simple solution I came up with: (Python 3)

def only_letters(tested_string):
    for letter in tested_string:
        if letter not in "abcdefghijklmnopqrstuvwxyz":
            return False
    return True

You can add a space in the string you are checking against if you want spaces to be allowed.


(1) Use str.isalpha() when you print the string.

(2) Please check below program for your reference:-

 str = "this";  # No space & digit in this string
 print str.isalpha() # it gives return True

 str = "this is 2";
 print str.isalpha() # it gives return False

Note:- I checked above example in Ubuntu.


Looks like people are saying to use str.isalpha.

This is the one line function to check if all characters are letters.

def only_letters(string):
    return all(letter.isalpha() for letter in string)

all accepts an iterable of booleans, and returns True iff all of the booleans are True.

More generally, all returns True if the objects in your iterable would be considered True. These would be considered False

  • 0
  • None
  • Empty data structures (ie: len(list) == 0)
  • False. (duh)

Actually, we're now in globalized world of 21st century and people no longer communicate using ASCII only so when anwering question about "is it letters only" you need to take into account letters from non-ASCII alphabets as well. Python has a pretty cool unicodedata library which among other things allows categorization of Unicode characters:

unicodedata.category('?')
'Lo'

unicodedata.category('A')
'Lu'

unicodedata.category('1')
'Nd'

unicodedata.category('a')
'Ll'

The categories and their abbreviations are defined in the Unicode standard. From here you can quite easily you can come up with a function like this:

def only_letters(s):
    for c in s:
        cat = unicodedata.category(c)
        if cat not in ('Ll','Lu','Lo'):
            return False
    return True

And then:

only_letters('Bzdrezylo')
True

only_letters('He7lo')
False

As you can see the whitelisted categories can be quite easily controlled by the tuple inside the function. See this article for a more detailed discussion.


You can leverage regular expressions.

>>> import re
>>> pattern = re.compile("^[a-zA-Z]+$")
>>> pattern.match("hello")
<_sre.SRE_Match object; span=(0, 5), match='hello'>
>>> pattern.match("hel7lo")
>>>

The match() method will return a Match object if a match is found. Otherwise it will return None.


An easier approach is to use the .isalpha() method

>>> "Hello".isalpha()
True
>>> "Hel7lo".isalpha()
False

isalpha() returns true if there is at least 1 character in the string and if all the characters in the string are alphabets.


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 re

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

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to conditional-statements

How to have multiple conditions for one if statement in python Excel - programm cells to change colour based on another cell Using OR & AND in COUNTIFS C error: Expected expression before int Conditional Replace Pandas SELECT query with CASE condition and SUM() Simpler way to check if variable is not equal to multiple string values? Replace all elements of Python NumPy Array that are greater than some value How can I check if a string only contains letters in Python? Check if year is leap year in javascript