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
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