srtring to int question

Jim Richardson warlock at eskimo.com
Sun Aug 13 15:23:48 EDT 2000


On Sun, 13 Aug 2000 11:42:05 +0200, 
 Alex Martelli, in the persona of <alex at magenta.com>,
 brought forth the following words...:

>"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.
>
>

Thanks, after the try: except was pointed out, I didn't bother with
regexps, (which was my first thought, which perhaps shows I wasn't 
thinking...) after remembering namespace issues on repeating a call to 
a function within a function :) I got it working and now it's pretty 
much done. Of course, the need I had for a julian date converter has
elapsed, but it was fun and informative none-the-less.

For anyone interested in the code, it's at
http://www.eskimo.com/~warlock/freesoft/opensource.html


-- 
Jim Richardson
	Anarchist, pagan and proud of it
WWW.eskimo.com/~warlock
	Linux, because life's too short for a buggy OS.




More information about the Python-list mailing list