我试图制作Julius Caesar Cipher程序,但是通过在句子的开头和结尾添加随机字母来增加一种扭曲。由于某些原因,当我输入长字符串时,打印时字符串的一部分会丢失。我正在使用python3。有人可以解释如何解决此问题以及为什么会发生这种情况吗?谢谢
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 - Python Julius Caesar密码程序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45892023/