带有空格的句子的 Vigenere Cipher

问题描述

我想为句子制作一个 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

怎么做?

解决方法

一种方法是使用 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.