如何检查变量是否为整数?
当前回答
如果你想写一个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
其他回答
在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
你可以做到的。
if type(x) is int:
在python中检查是非常简单的。你可以这样做:
假设你想检查一个变量是否是整数!
## For checking a variable is integer or not in python
if type(variable) is int:
print("This line will be executed")
else:
print("Not an integer")
如果你真的需要检查,那么最好使用抽象基类而不是具体类。对于一个整数,这意味着:
>>> import numbers
>>> isinstance(3, numbers.Integral)
True
这并没有将检查限制为仅int或仅int和long,而是还允许其他用户定义的行为为整数的类型工作。
你可以这样做:
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'
同样的事情会发生
推荐文章
- 用Python构建最小的插件架构
- model.eval()在pytorch中做什么?
- Tensorflow 2.0:模块“Tensorflow”没有属性“Session”
- 从环境文件中读入环境变量
- 在OSX 10.11中安装Scrapy时,“OSError: [Errno 1]操作不允许”(El Capitan)(系统完整性保护)
- 如何删除熊猫数据帧的最后一行数据
- 我如何在熊猫中找到数字列?
- 检查pandas数据框架索引中是否存在值
- 计算熊猫数量的最有效方法是什么?
- 如何在python中验证日期字符串格式?
- 用csv模块从csv文件中读取特定的列?
- 使用PyCrypto AES-256加密和解密
- “\d”在正则表达式中是数字吗?
- Python中的否定
- 列表推导式中的Lambda函数