Skip to content
Related Articles

Related Articles

Python – Split a String by Custom Lengths
  • Last Updated : 11 Oct, 2020

Given a String, perform split of strings on the basis of custom lengths.

Input : test_str = ‘geeksforgeeks’, cus_lens = [4, 3, 2, 3, 1] 
Output : [‘geek’, ‘sfo’, ‘rg’, ‘eek’, ‘s’] 
Explanation : Strings separated by custom lengths.
Input : test_str = ‘geeksforgeeks’, cus_lens = [10, 3] 
Output : [‘geeksforge’, ‘eks’] 
Explanation : Strings separated by custom lengths. 
 

Method #1 : Using slicing + loop

In this, we perform task of slicing to cater custom lengths and loop is used to iterate for all the lengths.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Multilength String Split
# Using loop + slicing
  
# initializing string
test_str = 'geeksforgeeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing length list
cus_lens = [5, 3, 2, 3]
  
res = []
strt = 0
for size in cus_lens:
      
    # slicing for particular length
    res.append(test_str[strt : strt + size])
    strt += size
      
# printing result 
print("Strings after splitting : " + str(res)) 

chevron_right


Output



The original string is : geeksforgeeks
Strings after splitting : ['geeks', 'for', 'ge', 'eks']

Method #2 : Using join() + list comprehension + next()

This is yet another way in which this task can be performed. In this, we perform task of getting character till length using next(),  iterator method, provides more efficient solution. Lastly, join() is used to convert each character list to string.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Multilength String Split
# Using join() + list comprehension + next()
  
# initializing string
test_str = 'geeksforgeeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing length list
cus_lens = [5, 3, 2, 3]
  
# join() performs characters to string conversion
# list comprehension provides shorthand to solve problem
stritr = iter(test_str)
res = ["".join(next(stritr) for idx in range(size)) for size in cus_lens]
      
# printing result 
print("Strings after splitting : " + str(res)) 

chevron_right


Output

The original string is : geeksforgeeks
Strings after splitting : ['geeks', 'for', 'ge', 'eks']

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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :