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

如何使用循环重写Python字符串格式化输出代码?

问题:如何用循环重写以下代码?

原代码:

fruits=['mango','fig','apple']

print(f"i have {fruits[0]},{fruits[1]} and {fruits[2]}")

预期输出:

i have mango,fig and apple

解决方案

如果需要用循环来实现,可以通过遍历列表元素并按格式拼接字符串:

方法一:显式循环拼接

fruits = ['mango', 'fig', 'apple']
output_str = "i have "
for index, fruit in enumerate(fruits):
    if index == len(fruits) - 1:
        output_str += f"and {fruit}"
    elif index == len(fruits) - 2:
        output_str += f"{fruit} "
    else:
        output_str += f"{fruit},"
print(output_str)

方法二:结合切片的简洁写法(基于循环逻辑)

如果允许用join配合切片(底层也是循环处理元素),代码会更简洁:

fruits = ['mango', 'fig', 'apple']
prefix = ', '.join(fruits[:-1])
print(f"i have {prefix} and {fruits[-1]}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 11:20:36