首页 > 解决方案 > 删除列表的元素,直到到达 Python 中的第一个空元素

问题描述

我有这个字符串列表

list = ['1', '2', '3', '4', '', '    5', '    ', '    6', '', '']

我想在第一个空字符串之后获取每个项目以获得此结果

list = ['    5', '    ', '    6', '', '']

请注意,我想留下后面的空字符串

我写了这个函数:

def get_message_text(list):
    for i, item in enumerate(list):
        del list[i]
        if item == '':
            break
    return list

但我无缘无故地得到这个错误的结果:

['2', '4', '    5', '    ', '    6', '', '']

有什么帮助吗?

标签: pythonstringlistfilter

解决方案


只需找到第一个空字符串的索引并对其进行切片:

def get_message_text(lst):
    try:
        return lst[lst.index("") + 1:]
    except ValueError:  # '' is not in list
        return [] # if there's no empty string then don't return anything

推荐阅读