[英]How to fix “IndexError: string index out of range” error in python
我最近开始在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
尝试使用其他while
循环条件:
index = 0
fruit = "potato"
while abs(index) < len(fruit):
index = index - 1
letter = fruit[index]
print(letter)
这将起作用。 当然,这只是为了学习,在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
fruit = "potato"
index = len(fruit)
while index > 0 :
index = index - 1
letter = fruit[index]
print(letter)
尝试这个:
>>> 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
这就是你要找的
index = 0
fruit = "potato"
while index > -(len(fruit)) :
index = index - 1
letter = fruit[index]
print(letter)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.