Python中的换位密码



我目前正在尝试用python编写一个换位密码。然而,我已经到了一个卡住的地步。

我的代码:

key = "german"
length = len(key)
plaintext = "if your happy and you know it clap your hands, clap your hands"
Formatted = "".join(plaintext.split()).replace(",","")
split = split_text(formatted,length)
def split_text(formatted,length):
return [formatted[i:i + length] for i in range(0, len(formatted), length)]
def encrypt():

我用它来计算字符串的长度,然后用长度来确定要在程序中创建多少列。所以它会创建这个:

GERMAN
IFYOUR
HAPPYA
NDYOUK
NOWITC
LAPYOU
RHANDS
CLAPYO
URHAND
S

这就是我被困的地方。因为我想让程序通过将列组合在一起来创建一个字符串。所以它会将每一列组合起来创建:

IHNNLRCUSFADOAHLRYPYWPAAH ..... 

我知道我需要某种循环,但不确定如何告诉程序创建这样的字符串。

感谢

您可以使用字符串的切片以6(长度)的步长获取字符串的每个字母

print(formatted[0::length])
#output:
ihnnlrcus

然后循环遍历range(length)中所有可能的起始索引,并将它们全部链接在一起:

def encrypt(formatted,length):
    return "".join([formatted[i::length] for i in range(length)])

注意,这实际上并没有使用split_text,而是直接使用formatted

print(encrypt(formatted,length))

使用split_text的问题是,你不能使用像zip这样的工具,因为它们在第一个迭代器停止时停止(所以因为最后一个组中只有一个字符,你只能从zip(*split)中获得一个组)

for i in zip("stuff that is important","a"):
    print(i)
#output:
("s","a")
#nothing else, since one of the iterators finished.

为了使用类似的东西,你必须重新定义zip的工作方式,允许一些迭代器完成并继续,直到所有迭代器都完成:

def myzip(*iterators):
    iterators = tuple(iter(it) for it in iterators)
    while True: #broken when none of iterators still have items in them
        group = []
        for it in iterators:
            try:
                group.append(next(it))
            except StopIteration:
                pass
        if group:
            yield group
        else:
            return #none of the iterators still had items in them

然后你可以用它来处理像这样的分割数据:

encrypted_data = ''.join(''.join(x) for x in myzip(*split))

最新更新