简体   繁体   中英

Breaking up a string into parts (not in order)

I have a problem, I would like to write a vigenere cipher but can't seem to be able to do it.

string='ihaveanappleinmybag' 
length=3 
#output:
list=['ivnpiyg','healnb','aapema']

I have a string and a keyword and I would like to make a list so that every 1st,2nd,3rd element in the string is one element in the list.
The list depends on the keyword so if the keyword would be 4, it would be broken in 4 parts with every 1st, 2nd, 3rd, 4th element being an element in the list

You can use basic slicing here:

kw = 3
[s[i::kw] for i in range(kw)]

['ivnpiyg', 'healnb', 'aapema']

Wrap this in a simple function to easily pass a keyword:

def cipher(s, kw):
    return [s[i::kw] for i in range(kw)]

>>> cipher(s, 4)
['iepib', 'hapna', 'anlmg', 'vaey']

>>> cipher(s, 5)
['ialy', 'hneb', 'aaia', 'vpng', 'epm']
new_list=[]
for i in range(0,length):
    new_list.append(''.join([string[start:start+1] for start in range(i,len(string),length)]))

Inpired by @user3483203

new_list=[]
for i in range(0,length):
    new_list.append(string[i::length])

You can zip the desired number of iterators:

i = iter(string)
list(map(''.join, zip(*zip(*(i for _ in range(length))))))

This returns:

['ivnpiy', 'healnb', 'aapema']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM