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


当前回答

如果您正在从一个文件中读取数据,并且您有一个具有多种数据类型值的数组或字典,那么以下内容将很有用。 只需检查变量是否可以类型转换为int(或您想强制执行的任何其他数据类型)。

try :
    int(a);
    #Variable a is int
except ValueError : 
    # Variable a is not an int

其他回答

如果你想写一个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

如果你只需要值,操作符。Index (__index__特殊方法)是我认为的方法。因为它应该适用于所有可以安全转换为整数的类型。例如,浮点数失败,整数,甚至没有实现Integral抽象类的花哨整数类都可以通过duck typing工作。

操作符。索引用于列表索引等。在我看来,它应该被更多地使用/推广。

事实上,我认为这是唯一正确的方法来获得整数值,如果你想确定浮点数,由于截断问题等被拒绝,它适用于所有整型(即numpy等),即使他们可能(还)不支持抽象类。

这就是引入__index__的目的!

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

例如:

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

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

text = get_text()

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

do_something(text)

你可以做到的。

if type(x) is int: