Pythonic way to determine if a string is a number

Tim Golden mail at timgolden.me.uk
Sun Feb 15 15:08:53 EST 2009


python at bdurham.com wrote:
> <code>
> # str_to_num.py
> 
> def isnumber( input ):
>     try:
>         num = float( input )
>         return True
> 
>     except ValueError:
>         return False


Just for the info, Malcolm, you don't actually
need to assign the result of float (input)
to anything if you don't need to use it. All
you're looking for is the exception. Let the
intepreter convert it and then throw it away.

Also, as an alternative style which can be more
appropriate depending on the structure and intention
of what you're doing, you can use the else: clause
of the try-except block.

try:
    float (input)
except ValueError:
    return False
else:
    return True

TJG



More information about the Python-list mailing list