首页 > 其他 > 详细

Pyhton 练习题

时间:2018-12-05 18:24:04      阅读:173      评论:0      收藏:0      [点我收藏+]
#############
练习
如果list中既包含字符串,又包含整数,由于非字符串类型没有lower()方法,所以列表生成式会报错:

>> L = [‘Hello‘, ‘World‘, 18, ‘Apple‘, None]
>> [s.lower() for s in L]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
AttributeError: ‘int‘ object has no attribute ‘lower‘
使用内建的isinstance函数可以判断一个变量是不是字符串:

>> x = ‘abc‘
>> y = 123
>> isinstance(x, str)
True
>> isinstance(y, str)
False
###########

答案:

L = [‘Hello‘, ‘World‘, 18, ‘Apple‘, None]
for s in L:
if isinstance(s, str):
L2.append(s)

####################

>> L2 = []
>> for s in L:
... if isinstance(s, str):
... L2.append(s)
...
>> L2
[‘Hello‘, ‘World‘, ‘Apple‘]

Pyhton 练习题

原文:http://blog.51cto.com/bobo5620301/2326518

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!