gpt4 book ai didi

Python凯撒密码解码

转载 作者:太空宇宙 更新时间:2023-11-04 00:44:43 24 4
gpt4 key购买 nike

我是 Python 的新手,决定制作我自己的凯撒密码加密器。我做了加密器,还可以,但是,解密器只能成功解密一个单词。如果我输入一个句子,它会将所有解密合并在一起。有解决此问题的简单方法吗?

def decrypt():
ciphertext = raw_input('Please enter your Encrypted sentence here:')
shift = input('Please enter its shift value: ')
space = []

cipher_ords = [ord(x) for x in ciphertext]
plaintext_ords = [o - shift for o in cipher_ords]
plaintext_chars = [chr(i) for i in plaintext_ords]
plaintext = ''.join(plaintext_chars)
print 'Decryption Successful'
print ""
print 'Your encrypted sentence is:', plaintext

decrypt()

最佳答案

我的建议是在每个空格处拆分您的 raw_input(),遍历拆分输入中的每个单词,然后将句子与空格重新连接在一起。这似乎是我能想到的最规范的解决方案:

def decrypt():
ciphertext = raw_input('Please enter your Encrypted sentence here:')
shift = int(raw_input('Please enter its shift value: '))
space = []

# creat a list of encrypted words.
ciphertext = ciphertext.split()

# creat a list to hold decrypted words.
sentence = []

for word in ciphertext:
cipher_ords = [ord(x) for x in word]
plaintext_ords = [o - shift for o in cipher_ords]
plaintext_chars = [chr(i) for i in plaintext_ords]
plaintext = ''.join(plaintext_chars)
sentence.append(plaintext)

# join each word in the sentence list back together by a space.
sentence = ' '.join(sentence)
print 'Decryption Successful\n'
print 'Your encrypted sentence is:', sentence

decrypt()

输出:

Please enter your Encrypted sentence here: lipps xlivi
Please enter its shift value: 4
Decryption Successful

Your encrypted sentence is: hello there

注意事项:

  • 永远不要只在 Python 2.x 中执行 input(),因为它隐含地使用了 eval() - 这可能非常危险。请改用 int(raw_input())
  • 我删除了您必须创建新行的额外打印语句。而是在您的第二个打印语句中附加一个新行。

关于Python凯撒密码解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40224830/

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