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

Python如何将列表中以指定字符开头的字符串与后一元素拼接

Python列表指定前缀字符串拼接实现方法

实现思路

遍历列表时通过索引控制处理节奏,检测到当前元素以指定字符开头时,将其与后一位元素拼接后加入结果列表,同时跳过下一位元素的单独处理,其余元素直接加入结果列表即可。

可运行代码

# 不要使用list作为变量名,会覆盖Python内置list类型
original_list = ['green', 'black', 'brown', 'yellow', 'red', 'pink', 'glow', 'big']
target_prefix = 'g'
new_list = []
index = 0
list_length = len(original_list)

while index < list_length:
    # 同时判断当前元素是否符合前缀要求,且存在下一位元素避免索引越界
    if original_list[index].startswith(target_prefix) and index + 1 < list_length:
        new_list.append(f"{original_list[index]} {original_list[index+1]}")
        # 跳过下一位元素的单独处理
        index += 2
    else:
        new_list.append(original_list[index])
        index += 1

print(new_list)

运行输出

['green black', 'brown', 'yellow', 'red', 'pink', 'glow big']

注意事项

  • 内置的str.startswith()方法原生支持前缀匹配,不需要手动截取字符串判断,代码可读性更高。
  • 代码中添加了index + 1 < list_length的边界判断,如果列表最后一个元素刚好以指定前缀开头,不会触发拼接逻辑,避免索引越界报错。
  • 如果需要实现大小写不敏感的匹配,可以将判断条件修改为original_list[index].lower().startswith(target_prefix.lower()),即可同时匹配g和G开头的元素。

内容的提问来源于stack exchange,提问作者Erwin Hidayat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 02:54:06