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


当前回答

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

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

其他回答

如果你想写一个Python 2-3兼容的代码

要测试一个值是否为整数(任何类型),你可以这样做:

# Python 2 and 3: 
import sys
if sys.version_info < (3,):
    integer_types = (int, long,)
else:
    integer_types = (int,)

>>> isinstance(1, integer_types)
True

# Python 2 only:
if isinstance(x, (int, long)):
     ...

# Python 3 only:
if isinstance(x, int):
    ...

来源:http://python3porting.com/differences.html

为什么不试试这样的方法呢:

if x%1 == 0: 
val=3
>>> isinstance(val,int ) 
True

将工作。

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

text = get_text()

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

do_something(text)

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

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