Change language

Python | Split a string into groups of n consecutive characters

| |

Examples :

  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 a line
# for every 3rd number

 
# Initialization string

string = "Geeksforgeeks"

 
# Define the split point

n = 3

  
# Using the comprehension list

out = [(string [i: i + n]) for i in range ( 0 , len (string), n)]

 
# Printout

print (out)

Output:

 [’Gee’,’ ksf’, ’org’,’ eek’, ’s’] 

Method # 2: Using zip_longest

# Python code to split the number string
# and the symbol in every 4th number

 
# Import

from itertools import zip_longest

  
# Group function using zip_longest to split

def group (n, iterable, fillvalue = None ):

args = [ iter (iterable)] * n

  return zip_longest (fillvalue = fillvalue, * args)

 
# Initialization string

str = ’123GeeksForGeeks4567’

 
# Split Point

n = 4

 
# list of separated lines

out_string = [’ ’ .join (lis) for lis in group (n, str, ’ ’) ]

 
# Initialize the output list

out_no = []

 
# Convert a list of strings to a list of integers

for a in out_string:

out_no.append (a)

 
# Print list

print (out_no)

Exit:

 [’123G’,’ eeks’, ’ForG’,’ eeks’, ’4567’]