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


当前回答

为什么不直接检查您想检查的值是否等于它本身转换为一个整数,如下所示?

def isInt(val):
    return val == int(val)

其他回答

考虑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。

如果你想检查不考虑Python版本(2。x vs . 3.x),使用六(PyPI)和它的integer_types属性:

import six

if isinstance(obj, six.integer_types):
    print('obj is an integer!')

在六个(一个非常轻量级的单文件模块)中,它只是这样做的:

import sys
PY3 = sys.version_info[0] == 3

if PY3:
    integer_types = int,
else:
    integer_types = (int, long)

如果您正在从一个文件中读取数据,并且您有一个具有多种数据类型值的数组或字典,那么以下内容将很有用。 只需检查变量是否可以类型转换为int(或您想强制执行的任何其他数据类型)。

try :
    int(a);
    #Variable a is int
except ValueError : 
    # Variable a is not an int

我以前遇到过这个问题,如果你的类型在if语句中使用它,让我们只是说你想让它返回true,你会把它输入到一行,(在所有的底线是真的需要看):

In [1]: test = 1

In [2]: test2 = 1.0

In [3]: type(test) == int
Out[3]: True

In [4]: type(test2) == int
Out[4]: False

In [5]: if type(x) == int is True:

你可以做同样的事情来检查它是否是一个浮点数,它是真还是假,并用来分配一个名称,(比如x,如果你知道我的意思的话)。

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

将工作。