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


当前回答

你也可以使用str.isdigit。尝试查找帮助(str.isdigit)

def is_digit(str):
      return str.isdigit()

其他回答

你可以这样做:

name = 'Bob'
if type(name) == str:
    print 'this works'
else:
    print 'this does not work'

它会返回'this works'…但是如果你将name改为int(1),那么它将返回'this does not work',因为它现在是一个字符串… 你也可以试试:

name = int(5)
if type(name) == int:
    print 'this works'
else:
    print 'this does not work'

同样的事情会发生

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

例如:

  n = 14
  if type(n)==int:
  return "this is an int"
import numpy as np

if (np.floor(x)-x == 0):
  return "this is an int"
#######################################
# Value_Is_Int
#######################################
def value_is_int(value):
    try:
        tempVal = int(value)
        return True
    except:
        return False

调用这个函数:

if value_is_int(value):
    print "Integer"
else:
    print "Not integer"

我可以检查数字是否是整数,包括像7.0这样的数字

def is_int(x):
    if x - round(x) == 0 :
        return True
    else:
        return False