5
votes

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'>
6
Huh... Does var = "Hello 20" "contain a number"? - NullUserException

6 Answers

12
votes
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
6
votes

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

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]: 
2
votes

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

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)
0
votes

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