python学习笔记(一)@TOC
删除列表里的空字符串
方法一:利用for…in 循环遍历列表,如果列表中有空字符串,利用remove删除空字符串
```python
words=['hello','good','yes','ok','']
for word in words:
if word=='':
words.remove(word)
print(words)
但是该代码有一定的错误,如果在words中存在多个空格,删除一个空格之后,其words会随时发生变化,导致无法正常删除空字符串,所以在使用for…in循环遍历列表时,最好不要对元素进行增删操作
方法二:利用while循环遍历列表,设置从0开始遍历,如果存在空字符串,则删除空字符串,同时令i-1,实现全部遍历实现
words=['hello','good','','','yes','ok','']
i=0
while i<len(words):
if words[i]=='':
words.remove(words[i])
i-=1
i+=1
print(words)
方法三:使用新列表覆盖旧列表
words=['hello','good','','','yes','ok','']
words2=[]
for word in words:
if word!='':
words2.append(word)
words=words2
print(words)