【发布时间】:2019-08-10 23:31:01
【问题描述】:
我想在 python 中使用 while 循环检查从最后一个字符到第一个字符的字符串。
Linux - Ubuntu - 我正在使用 Atom 文本编辑器。
fruit = 'banana'
letter = fruit[5]
length = len(fruit)
index = 5
while index > len(fruit):
letter = fruit[index]
print(letter)
index = index - 1
终端正确列出了字符,但这样做了两次,最后显示超出范围错误。检查:
a
n
a
n
a
b
a
n
a
n
a
b
Traceback (most recent call last):
File "youtube.py", line 5, in <module>
letter = fruit[index]
IndexError: string index out of range
【问题讨论】:
-
无法复制。发布的此代码不会进入循环。
-
我标记为可能的欺骗,但如果你需要使用while循环,只需写
while index >= 0——编辑:并以length = len(fruit) - 1开头跨度> -
嗯,是的,正如@Carcigenicate 提到的,您的代码肯定不会产生您记录的输出
标签: python