Newbie asks: How to do this line of C in Py?

Alex Martelli aleaxit at yahoo.com
Tue Jul 10 17:18:15 CEST 2001


"Steve S.L. Wong" <sailwong at alumni.cuhk.edu.hk> wrote in message
news:tkm2bef90nsic1 at news.supernews.com...
> if (sscanf(command, "%d", &num) != 1 )  {
> }

try: num = int(command)
except ValueError:
    print "some error (or whatever)"

Actually this depends on the exact semantics
of sscanf -- the Python version will tolerate
whitespace on either side of the sign and digits,
but not other extraneous characters -- and it's
been a while since I sscanf'd something, so I
don't precisely recall what (if anything) it
will tolerate in terms of 'extraneous chars'.

But anyway, the general approach of try/except
is how you try a string->whatever conversion,
while ready to handle the case in which the
conversion cannot be performed correctly.


Alex






More information about the Python-list mailing list