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


当前回答

import numpy as np

if (np.floor(x)-x == 0):
  return "this is an int"

其他回答

你可以做到的。

if type(x) is int:

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

例如:

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

一个简单的方法是直接检查除以1的余数是否为0。

if this_variable % 1 == 0:
    list.append(this_variable)
else:
    print 'Not an Integer!'

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

text = get_text()

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

do_something(text)

与其把事情过分复杂化,不如干脆简单一点

if type(var) is int: