如何检查变量是否为整数?


当前回答

一种更通用的方法将尝试检查整数和作为字符串给出的整数

def isInt(anyNumberOrString):
    try:
        int(anyNumberOrString) #to check float and int use "float(anyNumberOrString)"
        return True
    except ValueError :
        return False

isInt("A") #False
isInt("5") #True
isInt(8) #True
isInt("5.88") #False *see comment above on how to make this True

其他回答

>>> isinstance(3, int)
True

更多信息请看这里。

请注意,如果您正在寻找类似int的属性,这没有帮助。在这种情况下,你可能也想检查很长时间:

>>> isinstance(3L, (long, int))
True

我在Python源代码中见过这种针对数组/索引类型的检查,但我认为在C语言之外是看不到的。

令牌SO回复:你确定你应该检查它的类型吗?要么不要传递一个你不能处理的类型,要么不要试图智胜你潜在的代码重用者,他们可能有一个很好的理由不传递int给你的函数。

还有另一个选项可以进行类型检查。

例如:

  n = 14
  if type(n)==int:
  return "this is an int"

测试,如果object是一个字符串(适用于Python 2。*和Python 3。*)

text = get_text()

try:
    text = text+""
except:
    return "Not a string"

do_something(text)
val=3
>>> isinstance(val,int ) 
True

将工作。

如果变量像字符串一样输入(例如。“2010”):

if variable and variable.isdigit():
    return variable #or whatever you want to do with it. 
else: 
    return "Error" #or whatever you want to do with it.

在使用这个之前,我用try/except和检查(int(变量))解决了它,但它是较长的代码。我想知道在资源的使用和速度上是否有什么不同。