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


当前回答

你可以做到的。

if type(x) is int:

其他回答

你可以这样做:

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'

同样的事情会发生

你可以使用这个函数:

def is_int(x):    
    if type(x) == int:
       return True
    return False

测试:

print is_int('7.0') # False
print is_int(7.0) # False
print is_int(7.5) # False
print is_int(-1) # True

在numpy检查的存在,如..

isinstance(var, numbers.Integral)

. .(慢)或..

isinstance(var, (int, long, np.integer))

. .为了匹配所有类型变量,比如np.int8, np.int8。uint16,……

(PY3中Drop long)

从任何地方识别任何整数类对象都是一场棘手的猜谜游戏。检查

var & 0 == 0 

因为真理和非例外可能是一个很好的赌注。类似地,专门检查有符号整数类型:

var ^ -1 ==  -var - 1

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

text = get_text()

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

do_something(text)

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