Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 656
user2745401 Avatar asked Sep 06 '13 22:09

user2745401


People also ask

How do you check if a string has only letters?

Use the test() method to check if a string contains only letters, e.g. /^[a-zA-Z]+$/. test(str) . The test method will return true if the string contains only letters and false otherwise.

How do you check if a string contains only letters and digits Python?

Use string. ascii_letters if you use '[a-zA-Z]' regexps.


1 Answers

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 
like image 141
Martijn Pieters Avatar answered Oct 08 '22 03:10

Martijn Pieters