gpt4 book ai didi

python - Python 中的凯撒密码函数

转载 作者:太空狗 更新时间:2023-10-29 16:58:41 26 4
gpt4 key购买 nike

我正在尝试在 Python 中创建一个简单的 Caesar Cipher 函数,该函数根据用户的输入移动字母并在末尾创建一个最终的新字符串。唯一的问题是最终的密文只显示最后一个移位的字符,而不是包含所有移位字符的整个字符串。

这是我的代码:

plainText = raw_input("What is your plaintext? ")
shift = int(raw_input("What is your shift? "))

def caesar(plainText, shift):

for ch in plainText:
if ch.isalpha():
stayInAlphabet = ord(ch) + shift
if stayInAlphabet > ord('z'):
stayInAlphabet -= 26
finalLetter = chr(stayInAlphabet)
cipherText = ""
cipherText += finalLetter

print "Your ciphertext is: ", cipherText

return cipherText

caesar(plainText, shift)

最佳答案

我知道这个答案并没有真正回答您的问题,但我认为它还是有帮助的。这是使用字符串方法实现凯撒密码的另一种方法:

def caesar(plaintext, shift):
alphabet = string.ascii_lowercase
shifted_alphabet = alphabet[shift:] + alphabet[:shift]
table = string.maketrans(alphabet, shifted_alphabet)
return plaintext.translate(table)

事实上,由于字符串方法是用 C 语言实现的,我们将看到此版本的性能有所提高。这就是我认为的“pythonic”方式。

关于python - Python 中的凯撒密码函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8886947/

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