我得到错误:字符串索引超出范围

时间:2015-01-31 16:10:11

标签: python

我想知道差异

当我运行此代码时

message = "Three can keep a secret, if two of them are dead."
translated = ""
i  = len(message)
while i >= 0:
    translated = translated + message[i]
    i = i - 1
print translated    

我收到错误:

IndexError:字符串索引超出范围

当我把它改为:

message = "Three can keep a secret, if two of them are dead."
translated = ""
i  = len(message) - 1 
while i >= 0:
    translated = translated + message[i]
    i = i - 1
print translated    

它现在有效,但为什么!???

为什么我必须输入len(按摩) - 1

谢谢

2 个答案:

答案 0 :(得分:2)

索引从0开始。第一个元素的索引是0

所以最后一个元素的索引是......(facepalm)。

答案 1 :(得分:0)

使用短字符串,如str = "hello",它由5个字符组成。

str[0] is 'h'
srt[1] is 'e'
...
srt[4] is 'o'
str[5] does not exist!

这就是为什么你只能达到len(str)-1,索引从0开始,而不是1。