Как исправить ошибку «IndexError: строковый индекс вне диапазона» в python - PullRequest
1 голос
/ 04 июня 2019

Я недавно начал изучать Python в MOOC на Coursera.Я пытаюсь написать цикл 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 ]

1 голос
/ 04 июня 2019

Это будет работать. Конечно, просто ради обучения, есть лучшие способы сделать это на 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
1 голос
/ 04 июня 2019

Попробуйте использовать другое while условие цикла:

index = 0
fruit = "potato"
while abs(index) < len(fruit):
    index = index - 1
    letter = fruit[index] 
    print(letter)
0 голосов
/ 04 июня 2019

Попробуйте:

>>> 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
0 голосов
/ 04 июня 2019

Это то, что вы ищете

index = 0
fruit = "potato"
while index > -(len(fruit)) :
    index = index - 1
    letter = fruit[index]
    print(letter)
0 голосов
/ 04 июня 2019
fruit = "potato"
index = len(fruit)
while index > 0 :
    index = index - 1
    letter = fruit[index] 
    print(letter)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...