Skip to main content
 首页 » 编程设计

Python Julius Caesar 密码程序

2024年10月01日7sharpest

我正在尝试制作 Julius Caesar Cipher 程序,但通过在句子的开头和结尾添加一个随机字母来添加一个扭曲。出于某种原因,当我输入一个长字符串时,打印时字符串的一部分丢失了。我正在使用 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 参数,则替换 all 出现。这意味着您要删除的字符比您预想的要多。

如果你只想去掉字符串的第一个和最后一个字符,你可以这样做

words = cleartext[1:-1] 

这更简洁,因为您实际上并不关心第一个和最后一个字符是什么,您只是希望它们消失。