“如何修复”;索引器:字符串索引超出范围“;python中的错误

“如何修复”;索引器:字符串索引超出范围“;python中的错误,python,while-loop,Python,While Loop,我最近开始在Coursera上的MOOC学习Python。我正在尝试编写一个while循环,它从字符串中的最后一个字符开始,向后运行到字符串中的第一个字符,将每个字母打印在单独的一行上,除了向后 我已经写了代码,这是给我想要的输出,但它也给我一个错误 “索引器:字符串索引超出范围” index=0 水果=“土豆” 当索引时,尝试以下方法: >>> fruit = "potato" >>> fruit = fruit[::-1] >>> fru

我最近开始在Coursera上的MOOC学习Python。我正在尝试编写一个while循环,它从字符串中的最后一个字符开始,向后运行到字符串中的第一个字符,将每个字母打印在单独的一行上,除了向后

我已经写了代码,这是给我想要的输出,但它也给我一个错误

“索引器:字符串索引超出范围”

index=0
水果=“土豆”
当索引时,尝试以下方法:

>>> fruit = "potato"
>>> fruit = fruit[::-1]
>>> fruit
'otatop'
>>> for letter in fruit:
...     print(letter)
...
o
t
a
t
o
p
或者使用
while循环

>>> fruit = "potato"
>>> fruit = fruit[::-1]
>>> fruit
'otatop'
>>>  index = 0
>>> while index < len(fruit):
...     print(fruit[index])
...     index+=1
...
o
t
a
t
o
p
>>水果=“土豆”
>>>水果
>>>果
“奥塔普”
>>>索引=0
>>>而指数
这就是您要找的

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

尝试在循环条件下使用不同的

index = 0
fruit = "potato"
while abs(index) < len(fruit):
    index = index - 1
    letter = fruit[index] 
    print(letter)
index=0
水果=“土豆”
而abs(指数)
这将起作用。当然,这只是为了学习,在Python中有更好的方法

fruit = "potato"
index = len(fruit) -1 #Python indexes starts from 0!
while index >= 0 :
    letter = fruit[index]
    print(letter)
    index -= 1 #decrease at the END of the loop!
输出:

o
t
a
t
o
p

谢谢你的回复,如果上面的代码看起来很愚蠢,我很抱歉,我最近才开始学习。我试过你的建议,但不起作用。这段代码运行时没有任何错误,但输出似乎不正确。这是我得到的输出。o t a t o p o在输出的末尾添加了一个额外的“o”,OP希望使用while循环来完成此操作。@alec_Djin如果我使用
for
,还有什么问题吗。但我会尊重你的评论,并会编辑答案。谢谢你的帮助,我只需要用while编写这段代码loop@PrashantGonga我已经用while循环添加了答案。@mazingthingsaroundyou问题是OP问了一个涉及while循环的解决方案,而你用for循环回答。所以,从技术上讲,这是一个错误的答案。代码可以工作,但答案不符合问题的规格。谢谢,这工作非常好,没有任何错误。感谢您的帮助。老实说,我更喜欢我的答案,因为它不需要每次迭代都调用
abs()
函数。@PrashantGonga很乐意帮忙:P@alec_djinn好吧,好吧,但是我的,自我广告也不好
index = 0
fruit = "potato"
while abs(index) < len(fruit):
    index = index - 1
    letter = fruit[index] 
    print(letter)
fruit = "potato"
index = len(fruit) -1 #Python indexes starts from 0!
while index >= 0 :
    letter = fruit[index]
    print(letter)
    index -= 1 #decrease at the END of the loop!
o
t
a
t
o
p