我运行程序时收到此错误:
Traceback (most recent call last):
File "C:/Users/####/PycharmProjects/hw5/Homework5_Cepero.py", line 112, in <module>
decrypt()
File "C:/Users/####/PycharmProjects/hw5/Homework5_Cepero.py", line 78, in decrypt
encrypted.append({stringlist[i] - keylist[i]} % 29)
TypeError: list indices must be integers, not str
Process finished with exit code 1
代码如下:
Alphabet = ["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", ",", ".", "-"]
def encrypt():
count = 0
i = 0
output = []
encrypted = []
keylist = []
stringlist = []
string = raw_input("Please enter a string to encrypt: ")
string = string.replace(' ', '')
key = raw_input("Please enter the key you'd like to use: ")
keylength = len(key)
stringlength = len(string)
overlap = stringlength % keylength
leftovers = key[:overlap]
random = stringlength - overlap
random = stringlength / keylength
key = (int(random) * key) + leftovers
#convert Key to uppercase
for i in key:
number = Alphabet.index(i.upper())
keylist.append(number)
#convert String to uppercase
for i in string:
number = Alphabet.index(i.upper())
stringlist.append(number)
while count < stringlength:
encrypted.append((stringlist[i] + keylist[i]) % 29)
count += 1
i += 1
for N in encrypted:
output.append(Alphabet[N])
string = ''.join(output)
print" "
print"Output:"
print" "
print "The encoded text is:", string
print" "
def decrypt():
count = 0
i = 0
output = []
encrypted = []
keylist = []
stringlist = []
string = raw_input("Please enter a string to decrypt: ")
string = string.replace(' ', '')
key = raw_input("Please enter the key you'd like to use: ")
keylength = len(key)
stringlength = len(string)
overlap = stringlength % keylength
leftovers = key[:overlap]
random = stringlength - overlap
random = stringlength / keylength
key = (int(random) * key) + leftovers
#convert Key to uppercase
for i in key:
number = Alphabet.index(i.upper())
keylist.append(number)
#convert String to uppercase
for i in string:
number = Alphabet.index(i.upper())
stringlist.append(number)
while count < stringlength:
encrypted.append({stringlist[i] - keylist[i]} % 29)
count += 1
i += 1
for N in encrypted:
output.append(Alphabet[N])
string = ''.join(output)
print" "
print"Output:"
print" "
print "The decoded text is:", string
print" "
# main function
if __name__ == '__main__':
selection = ''
while selection != 3:
selection = raw_input("\n\nEnter 1 to encrypt, 2 to decrypt, or 3 to exit: ")
if selection == '1':
encrypt()
elif selection == '2':
decrypt()
elif selection == '3':
print "Thanks for using my program"
exit()
答案 0 :(得分:2)
在本声明中
encrypted.append((stringlist[i] + keylist[i]) % 29)
您使用的是i
,以前用于对字符串进行迭代。
for i in string:
因此,i
仍然具有字符串的最后一个字符。您正在使用该字符串索引列表。这就是为什么python会抛出这个错误。