python学习笔记之删除列表空字符串

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)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值