PolyGeo PolyGeo - 2 months ago 5x
Python Question

Testing if Python string variable holds number (int,float) or non-numeric str?

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?

The code below is real (and correct of course):

>>> strVar = "145"
>>> print type(strVar)
<type 'str'>

but is there a Python function or other method that will enable me to return 'int' from interrogating strVar set as above

Perhaps something like the nonsense code and results below ...

>>> print typeofvalue(strVar)
<type 'int'>

or more nonsense:

>>> print type(unquote(strVar))
<type 'int'>

import ast
def type_of_value(var):
       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:

return int