以下代码迭代并输出香蕉,我该如何更改它以反转输出?

The following code iterates and output banana, how can i change it to reverse the output?

我想修改这段代码,使输出与字符串 "banana"

反转
index = 0
fruit = "banana"
while index < len(fruit):
    letter = fruit[index]
    print (letter)
    index = index + 1

当前输出

b
a
n
a
n
a

预期输出

a
n
a
n
a
b

这个有效

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

但我强烈建议您检查并了解字符串索引的工作原理。

fruit = "banana"
rev_fruit = fruit[::-1]
print(rev_fruit)

#输出:ananab

试试这个方法。在 Python -1 表示最后位置,因此单词的 len(负)是切片的第一个位置。

因为Python范围不包括在内,你必须在这个场景中添加一个-1。否则它会打印“anana”。

最后,我们要从-1到-6,所以增量必须是-1。

word = "banana"
start = -1
end = (len(word) * -1) - 1
increment = -1

print(word[start:end:increment])