2017-10-10 107 views
1

我正在給出一個密碼,其中給出了文本輸入並且輸出是輸入,但是在字母表中移動了2,例如「hi」變成了「jk」。我遇到問題,將「y」變成「b」等等。純文本是一組輸入。 主要是2在Python中列表列表

charset=["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"] # characters to be encrypted 

def caesar_encrypt(plaintext,key): 

    plaintext = plaintext.upper() # convert plaintext to upper case 
    ciphertext = "" # initialise ciphertext as empty string 

    for ch in plaintext: 
     if ch == " ": 
      pass 
     else: 
      index = charset.index(ch) 
      newIndex = index + key 
      shiftedCharacter = charset[newIndex] 
      ciphertext += shiftedCharacter 
      print(ciphertext) 
    return ciphertext 
+4

試'newIndex = –

+1

在此壓痕只是普通弄亂這可能會導致問題(索引+鍵)%LEN(字符集)'(滿足_integer modulo_)。 – tadman

+0

在另一個說明中,'charset =「ABCDEFGHIJKLMNOPQRSTUVWXYZ」'這個詞同樣很好,並且更加緊湊。你甚至可以執行'import string',然後使用'string.ascii_uppercase'。 –

回答

2

只要改變:

newIndex = index + key 

要:

newIndex = (index + key) % len(charset) 

這樣,值將環繞優雅ÿ

Modulo (%) documentation

0

要改變,你可以試試這個:

import string 

converter = {string.ascii_uppercase[i]:string.ascii_uppercase[i+2] for i in range(24)} 
+0

據我所見,這不會繞過'z'。你需要模數,這已經被其他答案覆蓋了。 –