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


当前回答

你可以做到的。

if type(x) is int:

其他回答

从来没有。检查。类型。

这样做。总是这样。

try:
    some operation that "requires" an integer
except TypeError, e:
    it wasn't an integer, fail.

你可以做到的。

if type(x) is int:

如果变量像字符串一样输入(例如。“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(变量))解决了它,但它是较长的代码。我想知道在资源的使用和速度上是否有什么不同。

你可以这样做:

name = 'Bob'
if type(name) == str:
    print 'this works'
else:
    print 'this does not work'

它会返回'this works'…但是如果你将name改为int(1),那么它将返回'this does not work',因为它现在是一个字符串… 你也可以试试:

name = int(5)
if type(name) == int:
    print 'this works'
else:
    print 'this does not work'

同样的事情会发生

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

将工作。