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

如何修改Python遍历打印banana的代码,实现字符串字符倒序输出

代码调整方案

核心修改逻辑

原while循环是从字符串首索引(0)正序遍历,要实现倒序逐字符打印,仅需调整遍历的起始位置、循环判定条件和索引步进规则即可,改动最小的方案如下:

调整后的代码

index = len(fruit) - 1
fruit = "banana"
while index >= 0:
    letter = fruit[index]
    print(letter)
    index = index - 1

可选更简洁写法

如果不限制必须使用while循环,还可以用Python字符串切片特性直接实现,代码更短:

fruit = "banana"
for letter in fruit[::-1]:
    print(letter)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 13:39:03