You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除Python字符串列表首尾空字符串并合并内部连续空字符串?

解决Python列表的空字符串清理需求

嘿,这个需求咱们可以分三步来实现,每一步逻辑都很清晰,我给你拆解下:

1. 移除前置空字符串

咱们可以通过循环检查列表的第一个元素,只要是空字符串就弹出,直到遇到第一个非空元素为止:

x = ["", "", "test", "", "", "not empty", "", "yes", ""]

# 移除前置空字符串
while x and x[0] == "":
    x.pop(0)

2. 移除后置空字符串

和前置的逻辑类似,只是换成检查列表的最后一个元素:

# 移除后置空字符串
while x and x[-1] == "":
    x.pop()

3. 缩减内部连续空字符串为单个

这一步咱们可以遍历处理后的列表,维护一个结果列表。遇到空字符串时,只在结果列表的最后一个元素不是空的情况下才添加;非空元素直接添加即可:

# 处理内部连续空字符串
cleaned_list = []
for item in x:
    if item == "":
        # 避免连续添加空字符串
        if not cleaned_list or cleaned_list[-1] != "":
            cleaned_list.append(item)
    else:
        cleaned_list.append(item)

完整代码示例

把上面的步骤整合起来,运行后就能得到你想要的目标列表:

x = ["", "", "test", "", "", "not empty", "", "yes", ""]

# 移除前置空字符串
while x and x[0] == "":
    x.pop(0)

# 移除后置空字符串
while x and x[-1] == "":
    x.pop()

# 处理内部连续空字符串
cleaned_list = []
for item in x:
    if item == "":
        if not cleaned_list or cleaned_list[-1] != "":
            cleaned_list.append(item)
    else:
        cleaned_list.append(item)

print(cleaned_list)  # 输出: ['test', '', 'not empty', '', 'yes']

另外,如果你想追求更简洁的写法,也可以用迭代器结合条件判断来处理,但上面的写法更直观,容易理解和调试~

内容的提问来源于stack exchange,提问作者Christopher Costello

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:43:20