python - 索引错误: list index out of range error when reversing a list

标签 python python-3.x

当我输入以下内容时:

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/

相关文章:

python - 将 *args 作为列表传递时如何禁用 "E1120: No value for argument if"的 pylint 报告

python - 在 Python 中从 JSON 初始化嵌套类?

sockets - 改善PyMongo套接字接收

python - 如何获取对象属性的类型提示?

c++ - ctypes wintypes WCHAR 字符串 附加空格

python - numpy 数组 - 替换某些值

python - 如何在 Matplotlib 中反转轴并设置极坐标图的零位置?

python - 使用 Python rdflib : how to include literals in sparql queries?

python - 根据不同的列值将值分配给数据框中的列

python - 通过将数字附加到另一个 numpy 数组来创建 numpy 数组