Python – 在 K字符上拆分列表字符串
有时在处理数据时,我们可能会遇到需要对字符串执行拆分操作的问题,有时,我们可能还需要将它们执行到整体嵌套的字符串中。让我们讨论可以执行此任务的某些方式。
方法 #1:使用循环 + split()
上述功能的组合可用于执行此任务。在此,我们遍历每个列表字符串并执行手动拆分,然后使用循环将新元素添加到该列表中。
# Python3 code to demonstrate
# Split String of list on K character
# using loop + split()
# Initializing list
test_list = ['Gfg is best', 'for Geeks', 'Preparing']
# printing original list
print("The original list is : " + str(test_list))
K = ' '
# Split String of list on K character
# using loop + split()
res = []
for ele in test_list:
sub = ele.split(K)
res.extend(sub)
# printing result
print ("The extended list after split strings : " + str(res))
输出 :
The original list is : ['Gfg is best', 'for Geeks', 'Preparing']
The extended list after split strings : ['Gfg', 'is', 'best', 'for', 'Geeks', 'Preparing']
方法 #2:使用join() + split()
上述功能的组合可用于执行此任务。在此,我们加入拆分列表的所有元素,然后将它们中的每一个连接起来,使其被 K 拆分。
# Python3 code to demonstrate
# Split String of list on K character
# using join() + split()
# Initializing list
test_list = ['Gfg is best', 'for Geeks', 'Preparing']
# printing original list
print("The original list is : " + str(test_list))
K = ' '
# Split String of list on K character
# using join() + split()
res = K.join(test_list).split(K)
# printing result
print ("The extended list after split strings : " + str(res))
输出 :
The original list is : ['Gfg is best', 'for Geeks', 'Preparing']
The extended list after split strings : ['Gfg', 'is', 'best', 'for', 'Geeks', 'Preparing']