Python | Splitting string list by strings
Sometimes, while working with Python strings, we might have a problem in which we need to perform a split on a string. But we can have a more complex problem of having a front and rear string and need to perform a split on them. This can be multiple pairs for split. Let’s discuss certain way to solve this particular problem.
Method : Using loop + index() + list slicing
This task can be performed by using the above functionalities together. In this, we just loop along the pairs and get the desired indices using index(). Then list slicing is done to construct a new list of the desired slice and appended to form a new resultant list.
# Python3 code to demonstrate working of # Splitting string list by strings # using loop + index() + list slicing # initialize list test_list = ['gfg', 'is', 'best', "for", 'CS', 'and', 'Maths' ] # initialize split list split_list = [('gfg', 'best'), ('CS', 'Maths')] # printing original list print("The original list is : " + str(test_list)) # printing split list print("The split list is : " + str(split_list)) # Splitting string list by strings # using loop + index() + list slicing for start, end in split_list: temp1 = test_list.index(start) temp2 = test_list.index(end) + 1 test_list[temp1 : temp2] = [test_list[temp1 : temp2]] # printing result print("The resultant split list is : " + str(test_list)) |
The original list is : ['gfg', 'is', 'best', 'for', 'CS', 'and', 'Maths']
The split list is : [('gfg', 'best'), ('CS', 'Maths')]
The resultant split list is : [['gfg', 'is', 'best'], 'for', ['CS', 'and', 'Maths']]
Recommended Posts:
- Python | Splitting list on empty string
- Python | Splitting string to list of characters
- Python | Splitting string to list of characters
- Python | Splitting operators in String
- Python | Splitting Text and Number in string
- Python - Filter float strings from String list
- Python | Split strings and digits from string list
- Python | Sort given list of strings by part of string
- Python | Convert list of strings to space separated string
- Python | Remove empty strings from list of strings
- Python | Tokenizing strings in list of strings
- Python | Merge list of tuple into list by joining the strings
- Python | Filter list of strings based on the substring list
- Python | Convert list of tuples to list of strings
- Python | Convert List of lists to list of Strings
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


