sys.argv and while loop
Christopher Myers
chris.myers at ingenta.com
Wed May 8 13:12:54 EDT 2002
Julia Bell wrote:
>
> Thanks for all of the advice. I'm converting from perl, so I'm not used to
> thinking about the difference between a string and a number in general.
>
> (We are planning to upgrade our version of python in the next few months.)
>
> Now that I know I have to worry about type, what is the best way to determine
> if a string is convertible to a number (integer or float)?
>
> If I use string.atoi(variable) or string.atof(variable), but variable cannot
> be converted to an integer or float, I get an error. I'm just learning about
> catching exceptions, so I think I could figure out how to catch the error and
> do something appropriate if that's the recommended approach. But, is there a
> better way (perform the test before trying to do the conversion)?
>
> Julia Bell
>
I recommend something like the following (obviously commenting and
uncommenting where appropriate to test):
str="3.14159"
#str="10000"
#str="foo"
try:
num=string.atoi(str)
except ValueError:
try:
num=string.atof(str)
except:
num=str
if type(num) == type(1.0):
print "Do float stuff in here"
elif type(num) == type(1):
print "Do int stuff in here"
else:
print "Value does not convert to a number"
I'd be very interested to see if there's a simpler way, though.
--
Christopher Myers, Graduate Software Developer
Ingenta, Inc.
12 Bassett St.
Providence, RI 02903
ph: 401.331.2014 x 102
em: chris.myers at ingenta.com
aim: chrismyers001
More information about the Python-list
mailing list