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


当前回答

如果你想检查不考虑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)

其他回答

从来没有。检查。类型。

这样做。总是这样。

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

你可以做到的。

if type(x) is int:

这里有一个简单的例子,你可以确定一个整数

def is_int(x):
    print round(x),
    if x == round(x):
        print 'True',
    else:
        print 'False'

is_int(7.0)   # True
is_int(7.5)   # False
is_int(-1)    # True    

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

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

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

例如:

  n = 14
  if type(n)==int:
  return "this is an int"