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


当前回答

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

例如:

  n = 14
  if type(n)==int:
  return "this is an 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。

如果你只需要值,操作符。Index (__index__特殊方法)是我认为的方法。因为它应该适用于所有可以安全转换为整数的类型。例如,浮点数失败,整数,甚至没有实现Integral抽象类的花哨整数类都可以通过duck typing工作。

操作符。索引用于列表索引等。在我看来,它应该被更多地使用/推广。

事实上,我认为这是唯一正确的方法来获得整数值,如果你想确定浮点数,由于截断问题等被拒绝,它适用于所有整型(即numpy等),即使他们可能(还)不支持抽象类。

这就是引入__index__的目的!

如果你想写一个Python 2-3兼容的代码

要测试一个值是否为整数(任何类型),你可以这样做:

# Python 2 and 3: 
import sys
if sys.version_info < (3,):
    integer_types = (int, long,)
else:
    integer_types = (int,)

>>> isinstance(1, integer_types)
True

# Python 2 only:
if isinstance(x, (int, long)):
     ...

# Python 3 only:
if isinstance(x, int):
    ...

来源:http://python3porting.com/differences.html

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

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给你的函数。