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


当前回答

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

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

其他回答

如果变量像字符串一样输入(例如。“2010”):

if variable and variable.isdigit():
    return variable #or whatever you want to do with it. 
else: 
    return "Error" #or whatever you want to do with it.

在使用这个之前,我用try/except和检查(int(变量))解决了它,但它是较长的代码。我想知道在资源的使用和速度上是否有什么不同。

使用int函数提供帮助

intchecker = float(input('Please enter a integer: '))
intcheck = 0
while intcheck != 1:
    if intchecker - int(intchecker) > 0:
        intchecker = float(input("You didn't enter a integer. "
                                 "Please enter a integer: "))
    else:
        intcheck = 1
print('you have entered a integer')

如果你要这么做,那就这么做

isinstance(<var>, int)

除非你用的是python2。X是你想要的

isinstance(<var>, (int, long))

不要使用type。在Python中,这几乎从来都不是正确的答案,因为它阻碍了多态性的所有灵活性。例如,如果你继承int类型,你的新类应该注册为int类型,这种类型是不行的:

class Spam(int): pass
x = Spam(0)
type(x) == int # False
isinstance(x, int) # True

这遵循了Python的强多态性:您应该允许任何行为类似int型的对象,而不是强制它是int型。

BUT

然而,经典的Python心态是请求原谅比请求许可更容易。换句话说,不要检查x是否是整数;假设它是,如果不是,则捕获异常结果:

try:
    x += 1
except TypeError:
    ...

这种心态正慢慢被抽象基类的使用所取代,抽象基类允许您准确地注册对象应该具有的属性(添加哪些属性?乘?加倍?)通过使它继承一个特殊构造的类。这将是最好的解决方案,因为它将允许那些具有必要和足够属性的对象,但你必须阅读如何使用它的文档。

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

如果你想检查一个字符串是否只由数字组成,但转换为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。