Python | Split string in groups of n consecutive characters
Given a string (be it either string of numbers or characters), write a Python program to split the string by every nth character.
Examples:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Input : str = "Geeksforgeeks", n = 3 Output : ['Gee', 'ksf', 'oor', 'gee', 'ks'] Input : str = "1234567891234567", n = 4 Output : [1234, 5678, 9123, 4567]
Method #1: Using list comprehension
# Python code to split string# by every 3rd number # String initializationstring = "Geeksforgeeks" # Defining splitting pointn = 3 # Using list comprehensionout = [(string[i:i+n]) for i in range(0, len(string), n)] # Printing outputprint(out) |
Output:
['Gee', 'ksf', 'org', 'eek', 's']
Method #2: Using zip_longest
# Python code to split string of number# and character into every 4th number # Importingfrom itertools import zip_longest # Group function using zip_longest to splitdef group(n, iterable, fillvalue=None): args = [iter(iterable)] * n return zip_longest(fillvalue=fillvalue, *args) # String initializationstr = '123GeeksForGeeks4567' # Split pointn=4 # list of separated stringout_string = [''.join(lis) for lis in group(n, str, '')] # Output list initializationout_no = [] # Converting list of string into list of integerfor a in out_string: out_no.append(a) # Printing listprint(out_no) |
Output:
['123G', 'eeks', 'ForG', 'eeks', '4567']


