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_numb
Here's my simple way of doing it. Let's say that I'm looping through some strings and I want to add them to an array if they turn out to be numbers.
try:
myvar.append( float(string_to_check) )
except:
continue
Replace the myvar.apppend with whatever operation you want to do with the string if it turns out to be a number. The idea is to try to use a float() operation and use the returned error to determine whether or not the string is a number.
Updated after Alfe pointed out you don't need to check for float separately as complex handles both:
def is_number(s):
try:
complex(s) # for int, long, float and complex
except ValueError:
return False
return True
Previously said: Is some rare cases you might also need to check for complex numbers (e.g. 1+2i), which can not be represented by a float:
def is_number(s):
try:
float(s) # for int, long and float
except ValueError:
try:
complex(s) # for complex
except ValueError:
return False
return True
Casting to float and catching ValueError is probably the fastest way, since float() is specifically meant for just that. Anything else that requires string parsing (regex, etc) will likely be slower due to the fact that it's not tuned for this operation. My $0.02.
This code handles the exponents, floats, and integers, wihtout using regex.
return True if str1.lstrip('-').replace('.','',1).isdigit() or float(str1) else False
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:
def is_float(text):
try:
float(text)
# check for nan/infinity etc.
if text.isalpha():
return False
return True
except ValueError:
return False
For int
use this:
>>> "1221323".isdigit()
True
But for float
we need some tricks ;-). Every float number has one point...
>>> "12.34".isdigit()
False
>>> "12.34".replace('.','',1).isdigit()
True
>>> "12.3.4".replace('.','',1).isdigit()
False
Also for negative numbers just add lstrip()
:
>>> '-12'.lstrip('-')
'12'
And now we get a universal way:
>>> '-12.34'.lstrip('-').replace('.','',1).isdigit()
True
>>> '.-234'.lstrip('-').replace('.','',1).isdigit()
False