如何检查变量是否为整数?
当前回答
测试,如果object是一个字符串(适用于Python 2。*和Python 3。*)
text = get_text()
try:
text = text+""
except:
return "Not a string"
do_something(text)
其他回答
从来没有。检查。类型。
这样做。总是这样。
try:
some operation that "requires" an integer
except TypeError, e:
it wasn't an integer, fail.
import numpy as np
if (np.floor(x)-x == 0):
return "this is an int"
你可以这样做:
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'
同样的事情会发生
>>> isinstance(3, int)
True
更多信息请看这里。
请注意,如果您正在寻找类似int的属性,这没有帮助。在这种情况下,你可能也想检查很长时间:
>>> isinstance(3L, (long, int))
True
我在Python源代码中见过这种针对数组/索引类型的检查,但我认为在C语言之外是看不到的。
令牌SO回复:你确定你应该检查它的类型吗?要么不要传递一个你不能处理的类型,要么不要试图智胜你潜在的代码重用者,他们可能有一个很好的理由不传递int给你的函数。
考虑x = n**(1.0/m)的情况,其中n=10**5, m=5。 在Python中,x将为10.000000000000002,由于浮点算术运算,它不是整数。
所以我要检查一下
if str(float(x)).endswith('.0'): print "It's an integer."
我用下面的代码进行了测试:
for a in range(2,100):
for b in range(2,100):
x = (a**b)**(1.0/b)
print a,b, x, str(float(x)).endswith('.0')
它对所有a和b输出True。
推荐文章
- 在Python中重置生成器对象
- 用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中的否定