如何检查变量是否为整数?
当前回答
如果你想检查不考虑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)
其他回答
你可以这样做:
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'
同样的事情会发生
import numpy as np
if (np.floor(x)-x == 0):
return "this is an int"
你也可以使用str.isdigit。尝试查找帮助(str.isdigit)
def is_digit(str):
return str.isdigit()
如果你真的需要检查,那么最好使用抽象基类而不是具体类。对于一个整数,这意味着:
>>> import numbers
>>> isinstance(3, numbers.Integral)
True
这并没有将检查限制为仅int或仅int和long,而是还允许其他用户定义的行为为整数的类型工作。
如果你想检查一个字符串是否只由数字组成,但转换为int型没有帮助,你总是可以使用regex。
import re
x = "01234"
match = re.search("^\d+$", x)
try: x = match.group(0)
except AttributeError: print("not a valid number")
Result: x == "01234"
在这种情况下,如果x是"hello",将其转换为数值类型会抛出ValueError,但数据也会在此过程中丢失。使用正则表达式并捕获AttributeError将允许您确认字符串中的数字字符,例如,前导0。
如果你不想让它抛出AttributeError,而只是想寻找更具体的问题,你可以改变正则表达式,只检查匹配:
import re
x = "h01234"
match = re.search("\D", x)
if not match:
print("x is a number")
else:
print("encountered a problem at character:", match.group(0))
Result: "encountered a problem at character: h"
这实际上显示了问题发生的位置,而不使用异常。同样,这不是为了测试类型,而是测试字符本身。这比简单地检查类型要灵活得多,特别是当类型之间的转换可能会丢失重要的字符串数据时,比如前导0。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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中获得所有直接子目录