
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Split a String in Equal Parts using Grouper in Python
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
# 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
# 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.