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.