Python | Ways to split a string in different ways
The most common problem we have encountered in Python is splitting a string by a delimeter, But in some cases we have to split in different ways to get the answer. In this article, we will get substrings obtained by splitting string in different ways.
Examples:
Input : Paras_Jain_Moengage_best
Output : [‘Paras’, ‘Paras_Jain’, ‘Paras_Jain_Moengage’, ‘Paras_Jain_Moengage_best’]Input : chunky_2808_GFG_Codechef
Output : [‘chunky’, ‘chunky_2808’, ‘chunky_2808_GFG’, ‘chunky_2808_GFG_Codechef’]
Below are some ways to do the task.
Method #1: Using Iteration
# Python code to split string in substring manner # Input initialisation Input = "Geeks_for_geeks_is_best" # Split initialise split_string = Input.split('_') # Output list initialise Output = [] # Iteration for a in range(len(split_string)): temp = split_string[:a + 1] temp = "_".join(temp) Output.append(temp) # print output print(Output) |
[‘Geeks’, ‘Geeks_for’, ‘Geeks_for_geeks’, ‘Geeks_for_geeks_is’, ‘Geeks_for_geeks_is_best’]
Method 2: Using Itertools
# Python code to split string in substring manner # Importing from itertools import accumulate # Input initialisation Input = "Geeks_for_geeks_is_best" # Using accumulate Output = [*accumulate(Input.split('_'), lambda temp1, temp2 : '_'.join([temp1, temp2])), ] # Printing output print(Output) |
[‘Geeks’, ‘Geeks_for’, ‘Geeks_for_geeks’, ‘Geeks_for_geeks_is’, ‘Geeks_for_geeks_is_best’]
Recommended Posts:
- Python | Ways to split strings using newline delimiter
- Python | Ways to split strings on Uppercase characters
- Reverse string in Python (5 different ways)
- Find length of a string in python (4 ways)
- Ways to remove i'th character from string in Python
- Python | Ways to check string contain all same characters
- Python | Ways to find all permutation of a string
- Python | Ways to concatenate boolean to string
- Python | Ways to check if given string contains only letter
- Python | Ways to convert string to json object
- Python | Ways to convert list of ASCII value to string
- Python | Ways to count number of substring in string
- Python | Ways to remove n characters from start of given string
- Python | Ways to find nth occurrence of substring in a string
- Python | Ways to remove numeric digits from given string
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.



