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


当前回答

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

text = get_text()

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

do_something(text)

其他回答

从来没有。检查。类型。

这样做。总是这样。

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

if (np.floor(x)-x == 0):
  return "this is an 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'

同样的事情会发生

>>> isinstance(3, int)
True

更多信息请看这里。

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

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

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

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

考虑x = n**(1.0/m)的情况,其中n=10**5, m=5。 在Python中,x将为10.000000000000002,由于浮点算术运算,它不是整数。

所以我要检查一下

if str(float(x)).endswith('.0'): print "It's an integer."

我用下面的代码进行了测试:

for a in range(2,100):
    for b in range(2,100):
        x = (a**b)**(1.0/b)
        print a,b, x, str(float(x)).endswith('.0')

它对所有a和b输出True。