测试Python字符串变量是否包含数字(int,float)或非数字str?

时间:2011-10-07 03:36:39

标签: python

如果Python字符串变量有一个整数,浮点数或放在其中的非数字字符串,是否有办法轻松测试该值的“类型”?

以下代码是真实的(当然也是正确的):

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

但是有一个Python函数或其他方法可以让我从上面询问strVar集返回'int'

也许类似于下面的废话代码和结果......

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

或更多废话:

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

6 个答案:

答案 0 :(得分:11)

import ast
def type_of_value(var):
    try:
       return type(ast.literal_eval(var))
    except Exception:
       return str

或者,如果您只想检查int,请使用以下内容将第3行更改为阻止try内的内容:

int(var)
return int

答案 1 :(得分:6)

我会这样做:

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

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

    return str

答案 2 :(得分:4)

使用.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]: 

答案 3 :(得分:1)

您可以使用内置的isinstance()函数检查变量是否为数字:

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

这也适用于字符串和unicode文字类型:

isinstance(x, (str, unicode))

例如:

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

答案 4 :(得分:0)

我会使用正则表达式

def instring (a):

  if re.match ('\d+', a):
    return int(a)
  elsif re.match ('\d+\.\d+', a):
    return float(a)
  else:
    return str(a)

答案 5 :(得分:0)

这是一个简单的做法,没有导入

    try:
        if len(str(int(decdata))) == len(decdata): return 'int'
    except Exception:
        return 'not int'

当然's'是你要评估的字符串