What is the best possible way to check if a string can be represented as a number in Python?
The function I currently have right now is:
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling float
in the main function is even worse.
There is one exception that you may want to take into account: the string 'NaN'
If you want is_number to return FALSE for 'NaN' this code will not work as Python converts it to its representation of a number that is not a number (talk about identity issues):
Otherwise, I should actually thank you for the piece of code I now use extensively. :)
G.
For
int
use this:But for
float
we need some tricks ;-). Every float number has one point...Also for negative numbers just add
lstrip()
:And now we get a universal way:
RyanN suggests
But this doesn't quite work, because for sufficiently large floats,
x-1 == x
returns true. For example,2.0**54 - 1 == 2.0**54
I also used the function you mentioned, but soon I notice that strings as "Nan", "Inf" and it's variation are considered as number. So I propose you improved version of your function, that will return false on those type of input and will not fail "1e3" variants:
I was working on a problem that led me to this thread, namely how to convert a collection of data to strings and numbers in the most intuitive way. I realized after reading the original code that what I needed was different in two ways:
1 - I wanted an integer result if the string represented an integer
2 - I wanted a number or a string result to stick into a data structure
so I adapted the original code to produce this derivative:
You can generalize the exception technique in a useful way by returning more useful values than True and False. For example this function puts quotes round strings but leaves numbers alone. Which is just what I needed for a quick and dirty filter to make some variable definitions for R.