Split a string into equal parts (grouper in Python)

Existing Itertools used:
izip_longest (* iterables [, fillvalue]) : create an iterator that concatenates elements from each from repeatable elements. If the iterations are of unequal length, the missing values ​​are filled with the padding value. The iteration continues until the longest iteration is exhausted.

Performance:

  • Advanced tools offer the same high performance as the basic toolset .
  • Superior memory performance is supported by processing elements one at a time, rather than carrying everything iterated into memory at once.
  • Keeping the code small by tying tools together in a functional style that helps eliminate temporary variables .
  • High speed is achieved by preferring “vectorized” building blocks over using for loops and generators, which incur interpreter overhead.

Examples:

  Input:  str = ABCDEFG, l = 3  Output:  ABC DEF Gxx  Explaination:  Grouping characters of string in set of 3: ABC DEF Gxx. `x` is added to the set which doesn`t have 3 elements in it.  Input:  str = GEEKSFORGEEKS, l = 5  Output:  GEEKS FORGE EKSxx 

Below is the Python3 code:

# Python3 code for group recipe

 
#import existing itertool izip_longest

from itertools import izip_longest

 
# function for perch recipe

def grouper (iterable, n, fillvalue = `x` ):

 

# create & # 39; n & # 39; -blocks for the collection

  args = [ iter (iterable)] * n

  

# collect data into fixed-length blocks

# length & # 39; n & # 39; using izip_longest and store

# result as a list

ans = list (izip_longest (fillvalue = fillvalue, * args))

 

# (optional) loop to convert ANS to string

  t = len (ans)

for i in range < code class = "plain"> (t):

ans [i] = "". join (ans [i])

 

  # return ans as a string

return "" . join (ans) 

 

 
# Driver code

s = "ABCDEFG"

k = 3

 

result = grouper (s, k)

print (result) 

Exit :

 ABC DEF Gxx