Skip to content
Related Articles

Related Articles

Python – Split a String by Custom Lengths

Improve Article
Save Article
  • Last Updated : 08 Aug, 2022
Improve Article
Save Article

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 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))

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 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))

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)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!