Python|以不同方式拆分字符串的方法
我们在Python中遇到的最常见的问题是用分隔符拆分字符串,但在某些情况下我们必须以不同的方式拆分才能得到答案。在本文中,我们将得到通过不同方式拆分字符串得到的子字符串。
例子:
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’]
以下是一些完成任务的方法。
方法#1:使用迭代
# 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’]
方法2:使用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’]