Error checking for 'raw_input( )'?

eric_brake brakedon at hotmail.com
Wed Jun 6 18:27:52 EDT 2001


"Alex Martelli" <aleaxit at yahoo.com> wrote in message news:<9flcus01b04 at enews2.newsguy.com>...
> "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

not really, I was hoping there was a way like when I use a "input()"
field and someone tries to enter a letter or word. Of course a error
occurs then I can catch them with try/except statements. but since
"raw_input()" can accept any string, letters or numbers, it doesn't
error.



More information about the Python-list mailing list