5

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'>
1
  • 1
    Huh... Does var = "Hello 20" "contain a number"? Commented Oct 7, 2011 at 3:39

6 Answers 6

12
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
Sign up to request clarification or add additional context in comments.

4 Comments

Just beat me, but this is probably better.
You should just catch ValueError otherwise you'll swallow the NameError when ast isn't imported. +1 nonetheless.
@sdolan The problem is that literal_eval may raise many different errors... I'll import ast :)
Like @sdolan pointed out, but also look at catching SyntaxError: "This function raises SyntaxError if the compiled source is invalid, and TypeError if the source contains null bytes." This is from the docs of compile() which is what this function calls.
6

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

Comments

4

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 Comments

Thanks Rafael - have not tested because I did not recognise some of your syntax - but trust that it would work if I did. As it turns out my integer and floats could be negatives (latitude/longitude).
My fav (for simple int vs. str cases). But maybe the Inand Out stuff does more harm than good.
2

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

Comments

0

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)

4 Comments

you should add ^[+-]? and $ to your regexes... If OP wants scientific notation like 3e+12 you'll have to add ([eE][+-]\d+)?
@JBernardo: point taken... Also this sounds like a user input; so there should probably be more input validation leading to regexp than just "what type is it".
Thanks whitey04 - have not tested because I did not recognise some of your syntax - but trust that it would work if I did.
I can hardly imagine a less Pythonic approach to the task.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.