Pythonic way to determine if a string is a number

John Machin sjmachin at lexicon.net
Sun Feb 15 20:37:19 EST 2009


On Feb 16, 7:05 am, pyt... at bdurham.com wrote:
> Thanks for everyone's feedback. I believe my original post's code
> (updated following my signature) was in line with this list's feedback.
>
> Christian: Thanks for reminding me about exponential formats. My updated
> code accounts for these type of numbers. I don't need to handle inf or
> nan values. My original code's except catches an explicit ValueError
> exception per your concern about bare excepts.
>
> Malcolm
>
> <code>
> # str_to_num.py
>
> def isnumber( input ):
>     try:
>         num = float( input )
>         return True
>
>     except ValueError:
>         return False
>
> if __name__ == '__main__':
>     tests = """
>         12
>         -12
>         -12.34
>         .0
>         .
>         1 2 3
>         1 . 2
>
>         1e10
>         1E10
>         inf
>         nan
>
>         12 and text
>         just text
>     """
>
>     for test in tests.split( '\n' ):
>         print 'test (%0s), isnumber: %1s' % ( test.strip(), isnumber(
>         test ) )
> </code>

Do you care about numbers that are representable as an int, but are
treated as inf by float()?

For example:
| >>> s = '1' * 310
| >>> float(s)
| inf
| >>> a = int(s)
| >>> # OK



More information about the Python-list mailing list