如何检查变量是否为整数?
当前回答
一个简单的方法是直接检查除以1的余数是否为0。
if this_variable % 1 == 0:
list.append(this_variable)
else:
print 'Not an Integer!'
其他回答
如果你想写一个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
为什么不试试这样的方法呢:
if x%1 == 0:
val=3
>>> isinstance(val,int )
True
将工作。
测试,如果object是一个字符串(适用于Python 2。*和Python 3。*)
text = get_text()
try:
text = text+""
except:
return "Not a string"
do_something(text)
你也可以使用str.isdigit。尝试查找帮助(str.isdigit)
def is_digit(str):
return str.isdigit()
推荐文章
- 把if-elif-else语句放在一行中?
- 我如何结合两个数据框架?
- 如何计数列表中唯一值的出现
- 为什么Pycharm的检查人员抱怨“d ={}”?
- 如何JSON序列化集?
- 在python中,年龄从出生日期开始
- 使用pip安装SciPy
- 在Python中,我应该如何测试变量是否为None, True或False
- 如何在Python中从毫秒创建datetime ?
- 如何解窝(爆炸)在一个熊猫数据帧列,成多行
- 如何使用pip安装opencv ?
- 在pip冻结命令的输出中“pkg-resources==0.0.0”是什么
- 格式y轴为百分比
- 熊猫连接问题:列重叠但没有指定后缀
- 为什么空字典在Python中是一个危险的默认值?