2017-04-27 211 views
0

我在Python中製作一個加密程序,它不斷向我發送「字符串索引超出範圍」消息。字符串索引超出範圍 - Python

input = input("").lower() 
letters =["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] 
message = [] 
encryption = [] 
letter = 0 
code = 1 
wordletter = 0 
word = "baa" 

for i in range(len(input)): 

    code = 1 

    wordletter += 1 

    if wordletter > len(word): 
     wordletter = 0 

    code = letters.index(word[wordletter]) 

    if input[i] in letters: 
     letter = letters.index(input[i]) 
     letter += code 
     message.append(letter) 
    else: 
     message.append(input[i]) 

for i in range(len(message)): 
    encryption.append(letters[message[i]]) 

它說錯誤在第19行 - 就像這樣。

Traceback (most recent call last): 
    File "//x17/StudentHome/2023/a.nachmany16/Encrypter.py", line 19, in <module> 
    code = letters.index(word[wordletter]) 
IndexError: string index out of range 
>>> 

有人可以幫我嗎?

回答

1
if wordletter > len(word): 
    wordletter = 0 

由於Python使用從零開始的索引,因此條件應更改爲>=