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


当前回答

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

例如:

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

其他回答

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

import numpy as np

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

你可以做到的。

if type(x) is int:

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

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

如果你想检查一个字符串是否只由数字组成,但转换为int型没有帮助,你总是可以使用regex。

import re
x = "01234"
match = re.search("^\d+$", x)
try: x = match.group(0)
except AttributeError: print("not a valid number")

Result: x == "01234"

在这种情况下,如果x是"hello",将其转换为数值类型会抛出ValueError,但数据也会在此过程中丢失。使用正则表达式并捕获AttributeError将允许您确认字符串中的数字字符,例如,前导0。

如果你不想让它抛出AttributeError,而只是想寻找更具体的问题,你可以改变正则表达式,只检查匹配:

import re
x = "h01234"
match = re.search("\D", x)
if not match:
    print("x is a number")
else:
    print("encountered a problem at character:", match.group(0))

Result: "encountered a problem at character: h"

这实际上显示了问题发生的位置,而不使用异常。同样,这不是为了测试类型,而是测试字符本身。这比简单地检查类型要灵活得多,特别是当类型之间的转换可能会丢失重要的字符串数据时,比如前导0。