Pyhton 練習題

#############
練習
若是list中既包含字符串,又包含整數,因爲非字符串類型沒有lower()方法,因此列表生成式會報錯:app

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函數能夠判斷一個變量是否是字符串:ide

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)it

####################ast

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

相關文章
相關標籤/搜索