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

时间:2019-06-04 10:55:24

标签: python while-loop

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

我已经编写了可以给我想要的输出,但也给我一个错误的代码

  

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

index = 0
fruit = "potato"
while index <= len(fruit) :
    index = index - 1
    letter = fruit[index] 
    print(letter)
 Traceback (most recent call last):
      File "strings_01.py", line 8, in <module>
        letter = fruit[index]
    IndexError: string index out of range

5 个答案:

答案 0 :(得分:1)

尝试使用其他while循环条件:

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

答案 1 :(得分:1)

这将起作用。当然,这只是为了学习,在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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

尝试一下:

>>> fruit = "potato"
>>> fruit = fruit[::-1]
>>> fruit
'otatop'
>>> for letter in fruit:
...     print(letter)
...
o
t
a
t
o
p

或者用while loop

>>> fruit = "potato"
>>> fruit = fruit[::-1]
>>> fruit
'otatop'
>>>  index = 0
>>> while index < len(fruit):
...     print(fruit[index])
...     index+=1
...
o
t
a
t
o
p

答案 4 :(得分:0)

这就是您要寻找的

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