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


当前回答

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

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

其他回答

下面是这里提到的不同方法的总结:

Int (x) == x 尝试x = operator.index(x) isinstance (x, int) isinstance (x, numbers.Integral)

下面是它们如何应用于各种具有整数值的数值类型:

你可以看到它们不是100%一致的。Fraction和Rational在概念上是相同的,但是一个提供了.index()方法,而另一个没有。复杂类型不喜欢转换为int,即使实部是整数,虚部是0。

(np.int8|16|32|64(5)表示np.int8(5), np.int32(5)等行为相同)

你可以做到的。

if type(x) is 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,如果你知道我的意思的话)。

如果你想写一个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

从来没有。检查。类型。

这样做。总是这样。

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