Python – Split a String by Custom Lengths
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
# Python3 code to demonstrate working of# Multilength String Split# Using loop + slicing# initializing stringtest_str = 'geeksforgeeks'# printing original stringprint("The original string is : " + str(test_str))# initializing length listcus_lens = [5, 3, 2, 3]res = []strt = 0for size in cus_lens: # slicing for particular length res.append(test_str[strt : strt + size]) strt += size # printing resultprint("Strings after splitting : " + str(res)) |
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
# Python3 code to demonstrate working of# Multilength String Split# Using join() + list comprehension + next()# initializing stringtest_str = 'geeksforgeeks'# printing original stringprint("The original string is : " + str(test_str))# initializing length listcus_lens = [5, 3, 2, 3]# join() performs characters to string conversion# list comprehension provides shorthand to solve problemstritr = iter(test_str)res = ["".join(next(stritr) for idx in range(size)) for size in cus_lens] # printing resultprint("Strings after splitting : " + str(res)) |
Output
The original string is : geeksforgeeks Strings after splitting : ['geeks', 'for', 'ge', 'eks']
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Space Complexity: O(n)






Please Login to comment...