如何在Python中将字符串转换为2d数组?

时间:2015-07-03 14:29:56

标签: python-2.7

我正在尝试在python中实现Columnar转置算法。所以我需要将输入字符串转换为2d字符数组。我该怎么做?

1 个答案:

答案 0 :(得分:0)

来自Encrypting a columnar transposition cipher:查看split_len函数

def split_len(seq, length):
    return [seq[i:i + length] for i in range(0, len(seq), length)]

def encode(key, plaintext):

    order = {
        int(val): num for num, val in enumerate(key)
    }

    ciphertext = ''
    for index in sorted(order.keys()):
        for part in split_len(plaintext, len(key)):
            try:
                ciphertext += part[order[index]]
            except IndexError:
                continue

    return ciphertext

print(encode('3214', 'IHAVETWOCATS'))
#>>> HTAAWTIECVOS