I want to ask if there is a method to check if a value is any number? Is there maybe a "master class" for numbers. I do not want to check every case (int, float, complex). If there is not it is no problem.
In my specific code I now just check every case and than also if it is NaN but that is really annoying.
I have a similar question to data structures: Is there a method that returns whether a value is any of list, tuple, dict or set? Right now I am also checking them every time. So basically my code looks like this:
try:
value
if value==None: #none
raise Exception("Your value is none")
elif isinstance(value,str):
if not value.isnumeric(): #real String
return value
else: #number String
return (float(value))
elif isinstance(value,float):
if math.isnan(value): #nan
raise Exception("Your number is NaN")
elif abs(value)>abs(int(value)): #real float
pass #to-do deal with "real" floats
else: #integer
return int(value)
elif isinstance(value,int): #int
if math.isnan(value): #nan
raise Exception("Your number is NaN")
else:
return value
elif isinstance(value,tuple):
pass #to-do recursion
elif isinstance(value,list):
pass #to-do recursion
elif isinstance(value,dict):
pass #to-do recursion
elif isinstance(value,set):
return ("This tool does not support sets yet")
except NameError: #undefined
raise Exception("Your value is undefined")
But I feel like it could be much better if there was a method isnumeric() for all values not just strings, like in php.
Regarding my research, I could only find the String isnumeric()
method or obviously the type()
and isinstance()
method.
Please help me but do not tell me there is no better solution.
question from:
https://stackoverflow.com/questions/65853315/check-if-a-value-is-any-number-in-python 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…