I am validating the text input by a user so that it will only accept letters but not numbers. so far my code works fine when I type in a number (e.g. 56), it warns me that I should only type letters and when I type in letters it doesn't return anything (like it should do). My problem is that it accepts it when I start by typing letters followed by numbers e.g. (s45). what it does is accept the first letter but not the whole string. I need it to accept the whole string.
def letterCheck(aString):
if len(aString) > 0:
if re.match("[a-zA-Z]", aString) != None:
return ""
return "Enter letters only"
Use the re.fullmatch()
, which will only return matches if the whole string matches the pattern; make sure to add +
to ensure that one or more characters can be matched:
if re.fullmatch("[a-zA-Z]+", aString):
Alternatively, you can anchor the pattern to the start and end:
if re.match("^[a-zA-Z]+$", aString):
Here ^
anchors to the start of the string, $
to the end.
However, for your specific case, you'd be better off just using str.isalpha()
combined with str.isascii()
though:
if aString.isalpha() and aString.isascii():
str.isalpha()
is only true if there is at least 1 character and all characters are letters.str.isascii()
is only true if the string is empty or only consists of ASCII characters.Together, they are only true if all characters in the string are ASCII letters. No need to reach for the hefty regular expression hammer here:
>>> 'foobar'.isalpha()
True
>>> 'foobar'.isascii()
True
>>> 'foobar42'.isalpha()
False
>>> ''.isalpha()
False
>>> 'å'.isascii()
False