Python中的换位密码

2024-05-14 21:03:49 发布

您现在位置: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():

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

^{pr2}$

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

IHNNLRCUSFADOAHLRYPYWPAAH ..... 

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

谢谢


Tags: key字符串text程序密码yourlendef
1条回答
网友
1楼 · 发布于 2024-05-14 21:03:49

您可以使用字符串片段来获取字符串中的每个字母,步骤为6(长度)

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

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

^{pr2}$

注意,这实际上并没有使用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))

相关问题 更多 >

    热门问题