# 移除空字符串
# 方法一
a = ['hi','hello','','','world','']
b = []
for a1 in a:
if a1 != '':
b.append(a1)
a = b
print(a)
# 方法二
a = ['hi','hello','','','world','']
for a1 in a:
if a1 == '':
a.remove(a1)
print(a)
# ⚠️有bug,如果是连续的空字符串,会被漏掉,打印结果:['hi', 'hello', 'world', '']
# ⚠️因此不建议用for in循环作列表的增删操作
#方法三
a = ['hi','hello','','','world','']
i = 0
while i < len(a):
if a[i] == '':
a.remove(a[i])
i -= 1 # ⚠️此处如果不剪去一个下标往回检查,则也会漏掉一个‘’,打印结果变为:['hi', 'hello', 'world', '']
i += 1
print(a)
Python:移除空字符串
最新推荐文章于 2024-06-03 21:08:42 发布