如何检查变量是否为整数?
当前回答
如果你想检查不考虑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)
其他回答
从来没有。检查。类型。
这样做。总是这样。
try:
some operation that "requires" an integer
except TypeError, e:
it wasn't an integer, fail.
你可以做到的。
if type(x) is int:
这里有一个简单的例子,你可以确定一个整数
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
一种更通用的方法将尝试检查整数和作为字符串给出的整数
def isInt(anyNumberOrString):
try:
int(anyNumberOrString) #to check float and int use "float(anyNumberOrString)"
return True
except ValueError :
return False
isInt("A") #False
isInt("5") #True
isInt(8) #True
isInt("5.88") #False *see comment above on how to make this True
还有另一个选项可以进行类型检查。
例如:
n = 14
if type(n)==int:
return "this is an 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中获得所有直接子目录