2017-10-10 106 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'。你需要模数,这已经被其他答案覆盖了。 –