【发布时间】:2019-07-03 13:51:28
【问题描述】:
当我输入这个时:
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
【问题讨论】:
-
如果一个字符串是
x = list("hello"),它的长度是5,但是由于python索引是从0开始的,所以没有元素x[5]。最后一个元素是x[4]。所以试试x = len(str) - 1 -
x = len(str) - 1 -
为什么要让它变得复杂?
str[::-1]可以。另外,不要将您的字符串命名为str。
标签: python python-3.x