Split String of Size N in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string s and an integer n, we have to split the s into n-sized pieces.

So, if the input is like s = "abcdefghijklmn", n = 4, then the output will be ['abcd', 'efgh', 'ijkl', 'mn']

To solve this, we will follow these steps −

  • i:= 0
  • f:= a new list
  • while i < size of s, do
    • insert s[from index i to i+n-1] at the end of f
    • i := i + n
  • return f

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, s, n):
      i=0
      f=[]
      while(i<len(s)):
         f.append(s[i:i+n])
         i+=n
   return(f)
ob = Solution()
print(ob.solve("abcdefghijklmn", 4))

Input

"abcdefghijklmn", 4

Output

['abcd', 'efgh', 'ijkl', 'mn']
raja
Published on 22-Sep-2020 10:55:42
Advertisements