Transposition Cipher in Python
Question: Im currently trying to code a transposition cipher in python. however i have
reached a point where im stuck.

my code:

    
    
    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():
    

i use that to count the length of the string, i then use the length to
determine how many columns to create within the program. So it would create
this:

    
    
    GERMAN
    IFYOUR
    HAPPYA
    NDYOUK
    NOWITC
    LAPYOU
    RHANDS
    CLAPYO
    URHAND
    S
    

this is know where im stuck. as i want to get the program to create a string
by combining the columns together. so it would combine each column to create:

    
    
    IHNNLRCUSFADOAHLRYPYWPAAH ..... 
    

i know i would need a loop of some sort but unsure how i would tell the
program to create such a string.

thanks


Answer: you can use slices of the string to get each letter of the string in steps of
6 (length)

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

Then just loop through all the possible start indices in `range(length)` and
link them all together:

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

note that this doesn't actually use `split_text`, it would take `formatted`
directly:

    
    
    print(encrypt(formatted,length))
    

the problem with using the `split_text` you then cannot make use of tools like
`zip` since they stop when the first iterator stops (so because the last group
only has one character in it you only get the one group from `zip(*split)`)

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

In order to use something like that you would have to redefine the way zip
works by allowing some of the iterators to finish and continue until all of
them are done:

    
    
    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
    

then you can use this to process the split up data like this:

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

