2016-01-26 51 views
0

我想在python中創建一次性pad-esque密碼。爲此,我將所有純文本轉換爲ASCII代碼,然後將它們添加到一起,然後將它們轉換回常規字符。但是,當我試圖將兩個數字加在一起時,我就陷入了困境。這裏是我的代碼:如何在Python中添加來自不同列表的列表項?

#Creating initial variables 
plainText = str(input('Input your plain text \n --> ')).upper() 
key = str(input('Input your key. Make sure it is as long as your plain text.\n --> ')).upper() 

#>Only allowing key if it is the same size as the plain text 
if len(key) != len(plainText): 
    print('Invalid key. Check key length.') 
    key = str(input('Input your key. Make sure it is as long as your plain text. \n --> ')).upper() 
else: 
    plainAscii=[ord(i) for i in plainText] 
    keyAscii=[ord(k) for k in key] 

print (plainAscii) 
print (keyAscii) 

#Adding the values together and putting them into a new list 
cipherText=[] 
for i in range(0, len(key)): 
    x = 1 
    while x <= len(key): 
     item = plainAscii[x] + keyAscii[x] 
     cipherText.append(item) 
     x = x + 1 
print(cipherText) 

我打印列表,因爲我一直在進行測試。但是,僅在打印前兩個名單後返回此:

Traceback (most recent call last): 
    File "/Users/chuckii/Desktop/onetimepad.py", line 21, in <module> 
    item = plainAscii[x] + keyAscii[x] 
IndexError: list index out of range 

請忽略我的少年的用戶名,我把它當我是10.在此先感謝。

+0

你是否試圖用一次性的墊子做一些Vigenere加密? – Reti43

+0

我做到了,我完成了它 - 我是一個非常開心的人。 –

回答

1

編輯更高效:

cipherText=[] 

for i in range(len(key)): 
    for x in range(len(key)): 
     item = plainAscii[x] + keyAscii[x] 
     cipherText.append(item) 

print(cipherText) 

應該解決它!

+0

不幸的是,這並沒有解決它。我將x更改爲0,並得到了同樣的結果。 –

+0

將'while'<= len(key)'中的'<='改爲'<'。這應該解決它。 –

+0

非常感謝!現在情況好轉 –

相關問題