📜  Python|按字符串拆分字符串列表

📅  最后修改于: 2022-05-13 01:54:37.065000             🧑  作者: Mango

Python|按字符串拆分字符串列表

有时,在使用Python字符串时,我们可能会遇到需要对字符串执行拆分的问题。但是我们可能会遇到更复杂的问题,即拥有前后字符串,并且需要对它们执行拆分。这可以是多对进行拆分。让我们讨论解决这个特定问题的某种方法。

方法:使用循环+ index() +列表切片
可以通过结合使用上述功能来执行此任务。在这种情况下,我们只是沿着对循环并使用index()获得所需的索引。然后进行列表切片以构造所需切片的新列表并附加以形成新的结果列表。

# 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']]