📜  Python – 在出现前缀时拆分字符串

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

Python – 在出现前缀时拆分字符串

给定一个字符串列表,在出现前缀时执行字符串拆分。

方法#1:使用循环+startswith()

在此,我们迭代 List 的每个元素,并检查是否必须使用 startswith() 通过检查前缀来更改新列表,如果遇到前缀则创建新列表。

Python3
# Python3 code to demonstrate working of
# Split Strings on Prefix Occurrence
# Using loop + startswith()
 
# initializing list
test_list = ["geeksforgeeks", "best", "geeks", "and", "geeks", "love", "CS"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing prefix
pref = "geek"
 
 
res = []
for val in test_list:
     
    # checking for prefix
    if val.startswith(pref):
         
        # if pref found, start new list
        res.append([val])
    else:
         
        # else append in current list
        res[-1].append(val)
 
# printing result
print("Prefix Split List : " + str(res))


Python3
# Python3 code to demonstrate working of
# Split Strings on Prefix Occurrence
# Using loop + zip_longest() + startswith()
from itertools import zip_longest
 
# initializing list
test_list = ["geeksforgeeks", "best", "geeks", "and", "geeks", "love", "CS"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing prefix
pref = "geek"
 
 
res, temp = [], []
 
for x, y in zip_longest(test_list, test_list[1:]):
    temp.append(x)
     
    # if prefix is found, split and start new list
    if y and y.startswith(pref):
        res.append(temp)
        temp = []
res.append(temp)
 
# printing result
print("Prefix Split List : " + str(res))


输出
The original list is : ['geeksforgeeks', 'best', 'geeks', 'and', 'geeks', 'love', 'CS']
Prefix Split List : [['geeksforgeeks', 'best'], ['geeks', 'and'], ['geeks', 'love', 'CS']]

方法 #2:使用循环 + zip_longest() + startswith()

在此,我们压缩所有元素及其后续元素子列表,并使用startswith()检查前缀,如果找到,则附加结果。

Python3

# Python3 code to demonstrate working of
# Split Strings on Prefix Occurrence
# Using loop + zip_longest() + startswith()
from itertools import zip_longest
 
# initializing list
test_list = ["geeksforgeeks", "best", "geeks", "and", "geeks", "love", "CS"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing prefix
pref = "geek"
 
 
res, temp = [], []
 
for x, y in zip_longest(test_list, test_list[1:]):
    temp.append(x)
     
    # if prefix is found, split and start new list
    if y and y.startswith(pref):
        res.append(temp)
        temp = []
res.append(temp)
 
# printing result
print("Prefix Split List : " + str(res))
输出
The original list is : ['geeksforgeeks', 'best', 'geeks', 'and', 'geeks', 'love', 'CS']
Prefix Split List : [['geeksforgeeks', 'best'], ['geeks', 'and'], ['geeks', 'love', 'CS']]