Pythonic way to determine if a string is a number
sjmachin at lexicon.net
Mon Feb 16 02:37:19 CET 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.
> # str_to_num.py
> def isnumber( input ):
> num = float( input )
> return True
> except ValueError:
> return False
> if __name__ == '__main__':
> tests = """
> 1 2 3
> 1 . 2
> 12 and text
> just text
> for test in tests.split( '\n' ):
> print 'test (%0s), isnumber: %1s' % ( test.strip(), isnumber(
> test ) )
Do you care about numbers that are representable as an int, but are
treated as inf by float()?
| >>> s = '1' * 310
| >>> float(s)
| >>> a = int(s)
| >>> # OK
More information about the Python-list