Python- how do I use re to match a whole string

Question:

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"
Asked By: Thomas

||

Answers:

use boundaries in your regex + raw string to encode the regex, like this:

r"^[a-zA-Z]+$"
Answered By: Aprillion

Anchor it to the start and end, and match one or more characters:

if re.match("^[a-zA-Z]+$", aString):

Here ^ anchors to the start of the string, $ to the end, and + makes sure you match 1 or more characters.

You’d be better off just using str.isalpha() instead though. No need to reach for the hefty regular expression hammer here:

>>> 'foobar'.isalpha()
True
>>> 'foobar42'.isalpha()
False
>>> ''.isalpha()
False
Answered By: Martijn Pieters

You might consider using isalpha() on the string. It returns true if the string contains nothing but alphabetic characters, false otherwise.

if aString.isalpha():
   do something
else:
   handle input error
Answered By: sizzzzlerz

if you look for pretty pythonic writings, go for isalpha and isdecimal :

str = u"23443434";
print str.isdecimal();
Answered By: Louis
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.