Pythonic way to determine if a string is a number

Python Nutter pythonnutter at gmail.com
Mon Feb 16 02:04:54 EST 2009


Type casting seems to be the wrong way to go about this.

teststring = '15719'
teststring.isdigit()
returns True

That takes care of integers.

from string import digits
digits
'0123456789'

now you have all the digits and you can do set testing in your logic
to see if the teststring has anything in digits

A dumb way to test is alphanumeric

teststring2 = '105.22'
teststring2.isalnum()
returns True

now you can go on from there and test to further to eliminate
'abcd385laf8' which on alnum() also returns true.

Have fun,
Cheers,
PN


2009/2/16  <python at bdurham.com>:
> What's the Pythonic way to determine if a string is a number? By
> number I mean a valid integer or float.
>
> I searched the string and cMath libraries for a similar function
> without success. I can think of at least 3 or 4 ways to build my
> own function.
>
> Here's what I came up with as a proof-of-concept. Are there
> 'better' ways to perform this type of test?
>
> Thanks,
> Malcolm
>
> <code>
> def isnumber( input ):
>    try:
>        if '.' in input:
>            num = float( input )
>        else:
>            num = int( input )
>        return True
>
>    except ValueError:
>        return False
>
> if __name__ == '__main__':
>    tests = """
>        12
>        -12
>        -12.34
>        .0
>        .
>        1 2 3
>        1 . 2
>        just text
>    """
>
>    for test in tests.split( '\n' ):
>        print 'test (%0s), isnumber: %1s' % \
>          ( test.strip(), isnumber( test ) )
>
> </code>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list