如何检查变量是否为整数?
当前回答
与其把事情过分复杂化,不如干脆简单一点
if type(var) is int:
其他回答
如果你想检查不考虑Python版本(2。x vs . 3.x),使用六(PyPI)和它的integer_types属性:
import six
if isinstance(obj, six.integer_types):
print('obj is an integer!')
在六个(一个非常轻量级的单文件模块)中,它只是这样做的:
import sys
PY3 = sys.version_info[0] == 3
if PY3:
integer_types = int,
else:
integer_types = (int, long)
如果你想写一个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
在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")
这里有一个简单的例子,你可以确定一个整数
def is_int(x):
print round(x),
if x == round(x):
print 'True',
else:
print 'False'
is_int(7.0) # True
is_int(7.5) # False
is_int(-1) # True
你可以做到的。
if type(x) is int:
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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中获得所有直接子目录