Python | Ways to split a 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`]

Here are some ways to do it.

Method # 1: Using iteration

# Python code for splitting a string in a substring fashion

 
# Initialize input

Input = "Geeks_for_geeks_is_best"

 
# Divide ь initialization

split_string = Input . split ( `_` )

 
# Initialize the output list

Output = []

 
# Iteration

for a in range ( len (split_string)):

temp = split_string [: a + 1 ]

temp = " _ " . join (temp)

Output.append (temp)

 
# printout

print (Output)

Exit:

[ `Geeks`, `Geeks_for`, `Geeks_for_geeks`, `Geeks_for_geeks_is`, `Geeks_for_geeks_is_best`]

Method 2: Using Itertools

# Python code to split the string in a substring fashion

 
# Import

 

from itertools import accumulate

 
# Initialize input

Input = "Geeks_for_geeks_is_best"

 
# Usage to accumulate

Output = [ * accumulate ( Input . split ( `_` ), lambda temp1, temp2:

`_` . join ([temp1, temp2])),] < / p>

 
# Printout

print (Output)

Exit:

[`Geeks`, `Geeks_for`, `Geeks_for_geeks`, `Geeks_for_geeks_is`, `Geeks_for_geeks_is_best`]