0

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

Filnor
  • 1,290
  • 2
  • 23
  • 28
  • What code do you already have? – Mark Oct 23 '18 at 14:38
  • See [ask]. You should [edit] this question and show a [mcve] and ask a specific question. "I can't to it" is not a question; it is a request that someone write the code for you. You aren't going to get much traction asking for that here. Did you do a web search for "vigenère cipher python" because if you really just want the solution, it is out there. –  Oct 23 '18 at 15:21
  • Possible duplicate of [Modified Vigenere Cipher in python - Alphabet](https://stackoverflow.com/questions/21496303/modified-vigenere-cipher-in-python-alphabet) –  Oct 23 '18 at 15:23

3 Answers3

2

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']
user3483203
  • 50,081
  • 9
  • 65
  • 94
0
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])
mad_
  • 8,121
  • 2
  • 25
  • 40
-1

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']
blhsing
  • 91,368
  • 6
  • 71
  • 106