温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Pyhton 练习题

发布时间:2020-04-13 21:42:38 来源:网络 阅读:320 作者:bobo5620301hotm 栏目:编程语言

#############
练习
如果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']

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI