当我输入以下内容时:
def FirstReverse(str):
# code goes here
x = len(str)
s = list(str)
while x >= 0:
print s[x]
x = x - 1
# keep this function call here
# to see how to enter arguments in Python scroll down
print FirstReverse(raw_input())
我收到此错误
ERROR ::--Traceback (most recent call last):
File "/tmp/105472245/main.py", line 14, in <module>
print FirstReverse("Argument goes here")
File "/tmp/105472245/main.py", line 7, in FirstReverse
print s[x] IndexError: list index out of range
最佳答案
Python 索引从 0 开始。因此,对于字符串“Hello”,索引 0 指向“H”,索引 4 指向“o”。当你这样做时:
x = len(str)
您将 x 设置为 5,而不是最大索引 4。因此,请尝试以下操作:
x = len(str) - 1
另外,还有另一个指针。而不是:
x = x - 1
您可以简单地说:
x -= 1
关于python - 索引错误: list index out of range error when reversing a list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54607349/