我正在制作一个密码,其中给出了一个文本输入,输出是输入但是在字母表中沿着2移位,例如" hi"变成了" jk"。我在包装清单时遇到问题,以便" y"可以变成" b"等等。 明文是一组输入。 关键是2
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
答案 0 :(得分:2)
只需改变:
newIndex = index + key
要:
newIndex = (index + key) % len(charset)
这样,值将优雅地环绕
答案 1 :(得分:0)
要转移,你可以试试这个:
import string
converter = {string.ascii_uppercase[i]:string.ascii_uppercase[i+2] for i in range(24)}