srtring to int question
Alex Martelli
alex at magenta.com
Sun Aug 13 05:42:05 EDT 2000
"Jim Richardson" <warlock at eskimo.com> wrote in message
news:slrn8pbuah.1t3.warlock at gargoyle.myth...
[snip]
> OK, the question, I use raw_input to poll for the julian day, and
> then convert to int via int, but how do I check that the value from
raw_input
> is "intable"? that is, it works fine if I pass a number, but if I type in
> non-numerical characters, [a-zA-Z!@# etc] then the code errors on the
> int() function. Any pointers? thanks
You can use several approaches. Most idiomatic is perhaps:
try:
result=int(astring)
except ValueError:
result=0
or similar. I.e., the "it's easier to ask forgiveness than
permission" idiom (from Grace Murray Hopper's best-known
quote): try the operation, catch the exception if it fails;
it's easier than checking beforehand if the operation's
pre-requisites are in fact entirely satisfied.
In this specific case, the pre-reqs are simple enough that
you may choose to check them; as you're not interested in
negative numbers, you may want to accept just a string of
digits, easily checked with re. But I think try/except is
a better general idiom for such needs in Python.
Alex
More information about the Python-list
mailing list