【问题标题】:Vigenere Cipher for sentence with whitespacesVigenere Cipher 用于带有空格的句子
【发布时间】:2021-04-06 05:35:55
【问题描述】:

我想为句子制作一个 vigenere 密码程序。 例如消息是“介绍我最好的朋友卡莉”,关键字是“攀登”

y = "Introducing my best friend carly"
target_length = len(y)

def repeat_string(a_string, target_length):
    number_of_repeats = target_length // len(a_string) + 1
    a_string_repeated = a_string * number_of_repeats
    a_string_repeated_to_target = a_string_repeated[:target_length]
    return a_string_repeated_to_target

a_string = "climb"

print (y)
print(repeat_string(a_string, target_length))

输出是

Introducing my friend carly
climbclimbclimbclimbclimbcl

而我想要的输出是

Introducing my friend carly
climbclimbc li mbclim bclim

怎么做?

【问题讨论】:

    标签: python cryptography vigenere


    【解决方案1】:

    一种方法是使用 itertools 并遍历原始消息:

    import itertools
    y = "Introducing my best friend carly"
    target_length = len(y)
    a_string = "climb"
    
    
    def repeat_string(a_string,y):
        repeated_word = itertools.cycle(a_string)
        return "".join([next(repeated_word) if letter.isalpha() else letter for letter in y])
    
    
    
    print (y)
    print(repeat_string(a_string,y))
    

    输出:

    Introducing my best friend carly
    climbclimbc li mbcl imbcli mbcli
    

    编辑:这应该保留任何标点符号, 输入:

    y = "Introducing, my best friend carly.
    

    输出:

    Introducing, my best friend carly.
    climbclimbc, li mbcl imbcli mbcli.
    

    【讨论】:

    • 非常感谢!如果我想再添加一个条件,如果有标点符号,要保留标点符号怎么办?我在 string.punctuation 中添加了 elif 字母,但是出错了。
    • @c.jungc,我添加了答案。它保留了标点符号。不需要 elif 语句。还是我误解了你,你确实想解码标点符号?
    • 对不起,我的错,我跑错了。您的答案已经保留了标点符号
    猜你喜欢
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多