Error checking for 'raw_input( )'?

Alex Martelli aleaxit at yahoo.com
Wed Jun 6 15:58:51 CEST 2001


"eric_brake" <brakedon at hotmail.com> wrote in message
news:7b515e0f.0106060455.4093daa0 at posting.google.com...
> What is the best way to detect whether number or letter strings were
> entered into the "raw_input( )" field. I want to be able to send a
> error message to the user if they enter the incorrect type
> (numbers,letters,etc).

import string
transl = string.maketrans('','')    # dummy translation

myline = raw_input()

noletters = string.translate(myline, transl, string.letters)
nodigits = string.translate(myline, transl, string.digits)

def check(xname, original, translated):
    if original:
        print "the line was not empty"
    else:
        print "the line was empty"
        return
    if translated==original:
        print "there were no", xname
    else:
        print "there were some", xname
    if translated:
        print "there were some non-%s"%xname
    else:
        print "there were nothing but", xname

check('letters', myline, noletters)
check('digits', myline, nodigits)


Is this the sort of thing you want to do...?  Of course,
you can structure the code differently, but the general
idea of string.translate with a dummy translation table
to get a version with all characters of a certain kind
removed is pretty good & fast.

For checks that are much more sophisticated, you may want
to use regular expressions instead -- but in general
they're nowhere as simple as string stuff, for what
you CAN do with strings... and Keep It Simple, S*****
is The Prime Directive of programming...:-)


Alex






More information about the Python-list mailing list