If a Python string variable has had either an integer, floating point number or a non-numeric string placed in it, is there a way to easily test the \"type\" of that value?<
Here is a short hand to do it without ast import
try:
if len(str(int(decdata))) == len(decdata): return 'int'
except Exception:
return 'not int'
Of course 's' is the string you want to evaluate
I'd do it like this:
def typeofvalue(text):
try:
int(text)
return int
except ValueError:
pass
try:
float(text)
return float
except ValueError:
pass
return str
You can check if a variable is numeric using the built-in isinstance() function:
isinstance(x, (int, long, float, complex))
This also applies to string and unicode literal types:
isinstance(x, (str, unicode))
For example:
def checker(x):
if isinstance(x, (int, long, float, complex)):
print "numeric"
elif isinstance(x, (str, unicode)):
print "string"
>>> x = "145"
>>> checker(x)
string
>>> x = 145
>>> checker(x)
numeric
I'd use a regular expression
def instring (a):
if re.match ('\d+', a):
return int(a)
elsif re.match ('\d+\.\d+', a):
return float(a)
else:
return str(a)
use .isdigit():
In [14]: a = '145'
In [15]: b = 'foo'
In [16]: a.isdigit()
Out[16]: True
In [17]: b.isdigit()
Out[17]: False
In [18]:
import ast
def type_of_value(var):
try:
return type(ast.literal_eval(var))
except Exception:
return str
Or, if you only want to check for int, change the third line to block inside try
with:
int(var)
return int