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


当前回答

我在所有软件中使用的一个简单方法是这样的。它检查变量是否由数字组成。

test = input("Enter some text here: ")
if test.isdigit() == True:
   print("This is a number.")
else:
   print("This is not a number.")

其他回答

从来没有。检查。类型。

这样做。总是这样。

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

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

if type(var) is int:

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

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

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

如果变量像字符串一样输入(例如。“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(变量))解决了它,但它是较长的代码。我想知道在资源的使用和速度上是否有什么不同。