我正在尝试在 Python 中创建一个简单的凯撒密码函数,该函数根据用户的输入移动字母,并在末尾创建一个最终的新字符串。唯一的问题是,最终的密文仅显示最后一个移位的字符,而不是包含所有移位字符的整个字符串。
这是我的代码:
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”方式。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)