Sunday, January 25, 2009

Python: check if a string is a number

To check if a string represents a number, this may be used:def isnum(s):
try:
float(s)
except ValueError:
return False
return True

Examples:
In [57]: isnum('abs')
Out[57]: False

In [58]: isnum('2.5')
Out[58]: True

In [59]: isnum('-2.5')
Out[59]: True

In [60]: isnum("2e-3")
Out[60]: True

In [61]: isnum("2e-3 a")
Out[61]: False

In [62]: isnum("2e-3 ")
Out[62]: True

In [63]: isnum(" 1.1e+3 ")
Out[63]: True

In [63]: isnum(" 52 ")
Out[63]: True