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

If the Python string variable was either an integer, a floating-point number, or an invalid string placed in it, is there a way to easily check the "type" of this value?

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

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

but is there a Python function or another method that will allow me to return 'int' from the strVar poll above

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

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

or more bullshit:

>>> print type(unquote(strVar))
<type 'int'>
+5
source share
6 answers
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 lock inside trywith:

int(var)
return int
+11

:

def typeofvalue(text):
    try:
        int(text)
        return int
    except ValueError:
        pass

    try:
        float(text)
        return float
    except ValueError:
        pass

    return str
+6

.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

You can check if a variable is numeric using the built-in function isinstance():

isinstance(x, (int, long, float, complex))

This also applies to string and unicode literals:

isinstance(x, (str, unicode))

For instance:

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
+1
source

I would use regex

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
source

Here is a short hand to do this without importing ast

    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

0
source

All Articles