Program to encrypt a string using Vertical Cipher in Python

Suppose we have a string s and a number n, we have to rearrange s into n rows so that s can be selected vertically (top to down, left to right).

So, if the input is like s = "ilovepythonprogramming" n = 5, then the output will be ['ipnrn', 'lypag', 'otrm', 'vhom', 'eogi']

To solve this, we will follow these steps −

  • L := empty list
  • for i in range 0 to n - 1:
    • insert a string by taking each nth character starting from i, and insert into L
  • return L

Let us see the following implementation to get better understanding −


 Live Demo

class Solution:
   def solve(self, s, n):
      return [s[i::n] for i in range(n)]
ob = Solution()
s = "ilovepythonprogramming"
n = 5
print(ob.solve(s, n))


"ilovepythonprogramming", 5


['ipnrn', 'lypag', 'otrm', 'vhom', 'eogi']

Updated on: 05-Oct-2020


Kickstart Your Career

Get certified by completing the course

Get Started