Split a string in equal parts (grouper in Python)

PythonServer Side ProgrammingProgramming

In this tutorial, we are going to write a program that splits the given string into equal parts. Let's see an example.

Input

string = 'Tutorialspoint' each_part_length = 5

Output

Tutor ialsp ointX

Input

string = 'Tutorialspoint' each_part_length = 6

Output

Tutori alspoi ntXXXX

We are going to use the zip_longest method from the itertools module to achieve the result.

The method zip_longest takes iterators as argument. We can also pass the fillvalue for partitioning the string. It will return list of tuples that contains characters of equal number.

The zip_longest return a tuple on each iteration until the longest iterator in the given in exhausted. And the tuple contains given length of characters from the iterators.

Example

 Live Demo

# importing itertool module
import itertools
# initializing the string and length
string = 'Tutorialspoint'
each_part_length = 5
# storing n iterators for our need
iterator = [iter(string)] * each_part_length
# using zip_longest for dividing
result = list(itertools.zip_longest(*iterator, fillvalue='X'))
# converting the list of tuples to string
# and printing it
print(' '.join([''.join(item) for item in result]))

Output

If you run the above code, then you will get the following result.

Tutor ialsp ointX

Example

 Live Demo

# importing itertool module
import itertools
# initializing the string and length
string = 'Tutorialspoint'
each_part_length = 6
# storing n iterators for our need
iterator = [iter(string)] * each_part_length
# using zip_longest for dividing
result = list(itertools.zip_longest(*iterator, fillvalue='X'))
# converting the list of tuples to string
# and printing it
print(' '.join([''.join(item) for item in result]))

Output

If you run the above code, then you will get the following result.

Tutori alspoi ntXXXX

Conclusion

If you have doubts in the tutorial, mention them in the comment section.

raja
Published on 11-Jul-2020 06:59:06
Advertisements