成都创新互联网站制作重庆分公司

Pyhton练习题

#############
练习
如果list中既包含字符串,又包含整数,由于非字符串类型没有lower()方法,所以列表生成式会报错:

创新互联建站自2013年起,是专业互联网技术服务公司,拥有项目网站设计、成都网站设计网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元吴堡做网站,已为上家服务,为吴堡各地企业和个人服务,联系电话:18982081108

L = ['Hello', 'World', 18, 'Apple', None]
[s.lower() for s in L]
Traceback (most recent call last):
File "", line 1, in
File "", line 1, in
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练习题
URL地址:http://cxhlcq.com/article/jigogh.html

其他资讯

在线咨询

微信咨询

电话咨询

028-86922220(工作日)

18980820575(7×24)

提交需求

返回顶部