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

Python循环打印列表元素如何按要求添加分隔符、空格和换行

问题排查

你的代码存在两个核心问题:

  • 仅对非末尾元素做了输出处理,完全没有打印列表的最后一个元素,自然无法输出末尾要求的空格和换行
  • 通过值判断是否为末尾元素的逻辑有漏洞:如果列表存在重复值,会出现误判,比如输入90 92 90时,第一个90会被错误识别为末尾元素,导致输出异常
修复代码

方案1:适配原有循环逻辑修改

用索引判断是否为末尾元素,单独处理末尾元素的输出格式:

user_input = input()
hourly_temperature = user_input.split()

for idx, item in enumerate(hourly_temperature):
    if idx != len(hourly_temperature) - 1:
        print(item, end=" -> ")
    else:
        # 末尾元素后加空格,print默认自带换行符,刚好符合要求
        print(item, end=" \n")

方案2:更简洁的字符串拼接实现

Python中处理这类元素间隔拼接的需求,优先用str.join()方法,代码更简洁执行效率也更高:

user_input = input()
hourly_temperature = user_input.split()
# 用指定分隔符拼接所有元素,末尾加空格后打印,print自带换行符
print(" -> ".join(hourly_temperature), end=" \n")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 07:06:04