我正在尝试制作朱利叶斯·凯撒密码程序,但通过在句子的开头和结尾添加一个随机字母来添加一个扭曲。由于某种原因,当我输入长字符串时,打印时该字符串的一部分会丢失。我正在使用 python 3。有人可以解释如何解决这个问题以及为什么会发生这种情况吗?谢谢
import random
alpha = 'abcdefghijklmnopqrstuvwxyz'
alphaupper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def encode(cleartext):
global alpha
global alphaupper
words = cleartext
cyphertext = ""
for char in words:
if char in alphaupper:
newpos = (alphaupper.find(char) + 13) % 26
cyphertext += alphaupper[newpos]
elif char in alpha:
newpos = (alpha.find(char) + 13) % 26
cyphertext += alpha[newpos]
else:
cyphertext += char
cyphertext = alpha[random.randrange(len(alpha) - 1)] + cyphertext + alpha[random.randrange(len(alpha) - 1)]
return cyphertext
def decode(cleartext):
global alpha
global alphaupper
words = cleartext.replace(cleartext[len(cleartext) - 1], "")
words = words.replace(words[0], "")
cyphertext = ""
for char in words:
if char in alphaupper:
newpos = (alphaupper.find(char) + 13) % 26
cyphertext += alphaupper[newpos]
elif char in alpha:
newpos = (alpha.find(char) + 13) % 26
cyphertext += alpha[newpos]
else:
cyphertext += char
return cyphertext
print("Julias Ceasar 13 letter shift")
def men():
words = input("Would you like to decode or encode: ")
if "decode" in words:
words = input("What would you like to decode: ")
print(decode(words))
print('\n')
men()
elif "encode" in words:
words = input("What would you like to encode: ")
print(encode(words))
print('\n')
men()
else:
print("Could not understand please try again")
print('\n')
men()
if __name__ == "__main__":
men()
输出:
Julias Ceasar 13 letter shift
Would you like to decode or encode: encode
What would you like to encode: This program deletes parts of this string for some reason
编码:
yGuvf cebtenz qryrgrf cnegf bs guvf fgevat sbe fbzr ernfbas
解码:
Would you like to decode or encode: decode
What would you like to decode: yGuvf cebtenz qryrgrf cnegf bs guvf fgevat sbe fbzr ernfbas
最终解码的句子:
This program deletes parts o this string or some reason
Would you like to decode or encode:
最佳答案
看起来问题是,在解码时,你这样做
words = cleartext.replace(cleartext[len(cleartext) - 1], "")
words = words.replace(words[0], "")
str.replace
如果您不包含可选的第三个 count
参数,则替换所有出现的情况。这意味着您删除的字符数量超出了您的预期。
如果您只想删除字符串中的第一个和最后一个字符,您可以执行类似的操作
words = cleartext[1:-1]
这更干净,因为您实际上并不关心第一个和最后一个字符是什么,您只是希望它们消失。
关于Python 朱利叶斯·凯撒密码程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45892023/