如何检查变量是否为整数?
当前回答
如果你想写一个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
其他回答
如果你真的需要检查,那么最好使用抽象基类而不是具体类。对于一个整数,这意味着:
>>> import numbers
>>> isinstance(3, numbers.Integral)
True
这并没有将检查限制为仅int或仅int和long,而是还允许其他用户定义的行为为整数的类型工作。
在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
val=3
>>> isinstance(val,int )
True
将工作。
你可以这样做:
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 isInt(val):
return val == int(val)
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录