Python – Split a String by Custom Lengths
Last Updated :
17 Apr, 2023
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
test_str = 'geeksforgeeks'
print ( "The original string is : " + str (test_str))
cus_lens = [ 5 , 3 , 2 , 3 ]
res = []
strt = 0
for size in cus_lens:
res.append(test_str[strt : strt + size])
strt + = size
print ( "Strings after splitting : " + str (res))
|
Output
The original string is : geeksforgeeks
Strings after splitting : ['geeks', 'for', 'ge', 'eks']
Time Complexity: O(n), where n is the length of the string
Auxiliary Space: O(n), length of the res string
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
test_str = 'geeksforgeeks'
print ( "The original string is : " + str (test_str))
cus_lens = [ 5 , 3 , 2 , 3 ]
stritr = iter (test_str)
res = ["".join( next (stritr) for idx in range (size)) for size in cus_lens]
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)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...