gpt4 book ai didi

python - 检查符号和大写/小写以使用凯撒密码进行加密?

转载 作者:太空宇宙 更新时间:2023-11-03 23:56:26 26 4
gpt4 key购买 nike

我尝试了几个小时来制作一个简单的 ceasar 密码加密程序。它终于奏效了。但它只能加密没有空格和符号的文本。我不知道如何将这些东西的检查部分实现到代码中。对使代码更清洁和 DRY 的批评者表示赞赏。谢谢。

我尝试实现功能的代码:

#Taking Input String + converting to list
message = input("Enter the message for encrypting: ")
message_list = list(message)

#Taking Input Cipher
cipher = int(input("Enter shifting value (1-26): "))

#Alphabet
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"]

#Defining variable
encrypted_message = []

#Shifting
for letter in message_list:
if letter not in alphabet:
encrypted_message.append(letter)
else:
#Getting Index of the letter in alphabet
letter_position = alphabet.index(letter)
#Getting the shifting value for the letter
shifting_value = letter_position + cipher
#Getting the shifted letter
shifted_letter = alphabet[shifting_value]
#Adding the corresponding letter to the encrypted message
encrypted_message.append(shifted_letter)

#Output
print("Original Message: " + message)
print("Encrypted Message: " + str(encrypted_message))
print("Cipher: " + str(cipher))

它应该做什么: 用空格和符号加密消息(凯撒密码),

它在做什么: 发生异常:IndexError列表索引超出范围

最佳答案

IndexError list index out of range 错误发生是因为您忘记了模数。没有模数,

shifting_value = letter_position + cipher

此行的值将高于您正在索引的数组。记住,凯撒密码是

c = p + 3 mod 26

所以这条线一定是

shifting_value = (letter_position + cipher) % 26

  • 注意 1:cipher 在这里不是一个好的变量名。应该是 shiftAmount。

  • 注意2:如果要将列表组合成字符串,使用

    str1 = ''.join(encrypted_message)

关于python - 检查符号和大写/小写以使用凯撒密码进行加密?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57581474/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com