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

Pol*_*Geo 5 python

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

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

>>> strVar = "145"
>>> print type(strVar)
<type 'str'>
>>>
Run Code Online (Sandbox Code Playgroud)

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

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

>>> print typeofvalue(strVar)
<type 'int'>
Run Code Online (Sandbox Code Playgroud)

或更多废话:

>>> print type(unquote(strVar))
<type 'int'>
Run Code Online (Sandbox Code Playgroud)

JBe*_*rdo 12

import ast
def type_of_value(var):
    try:
       return type(ast.literal_eval(var))
    except Exception:
       return str
Run Code Online (Sandbox Code Playgroud)

或者,如果您只想检查int,请将第三行更改为阻止内部try:

int(var)
return int
Run Code Online (Sandbox Code Playgroud)

  • 您应该只捕获ValueError,否则当未导入ast时将吞下NameError。但是+1。 (2认同)

Mic*_*man 6

我这样做:

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

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

    return str
Run Code Online (Sandbox Code Playgroud)