如何检查变量是否为整数?
当前回答
从来没有。检查。类型。
这样做。总是这样。
try:
some operation that "requires" an integer
except TypeError, e:
it wasn't an integer, fail.
其他回答
如果你想写一个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(input('enter = '))==int:
print 'Entered number is an Integer'
else:
print 'Entered number isn't an Integer'
这将检查number是否为整数
我在所有软件中使用的一个简单方法是这样的。它检查变量是否由数字组成。
test = input("Enter some text here: ")
if test.isdigit() == True:
print("This is a number.")
else:
print("This is not a number.")
在这里找到了一个关于SO本身的相关问题。
Python开发人员倾向于不检查类型,而是执行特定于类型的操作并捕获TypeError异常。但如果你不知道类型,那么你有以下。
>>> i = 12345
>>> type(i)
<type 'int'>
>>> type(i) is int
True
推荐文章
- 在python中,年龄从出生日期开始
- 使用pip安装SciPy
- 在Python中,我应该如何测试变量是否为None, True或False
- 如何在Python中从毫秒创建datetime ?
- 如何解窝(爆炸)在一个熊猫数据帧列,成多行
- 如何使用pip安装opencv ?
- 在pip冻结命令的输出中“pkg-resources==0.0.0”是什么
- 格式y轴为百分比
- 熊猫连接问题:列重叠但没有指定后缀
- 为什么空字典在Python中是一个危险的默认值?
- 在Python中,冒号等于(:=)是什么意思?
- Python "SyntaxError:文件中的非ascii字符'\xe2' "
- 如何从psycopg2游标获得列名列表?
- Python中dict对象的联合
- 如何有效地比较两个无序列表(不是集合)?