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

当需要根据前缀的出现对字符串进行拆分时,定义两个空列表,并定义一个前缀值。一个简单的迭代与 'append' 方法一起使用。

示例

以下是相同的演示 -

from itertools import zip_longest

my_list = ["hi", 'hello', 'there',"python", "object", "oriented", "object", "cool", "language", 'py','extension', 'bjarne']

print("名单是: " )
print(my_list)

my_prefix = "python"
print("前缀是:")
print(my_prefix)

my_result, my_temp_val = [], []

for x, y in zip_longest(my_list, my_list[1:]):
my_temp_val.append(x)
   if y and y.startswith(my_prefix):
      my_result.append(my_temp_val)
      my_temp_val = []

my_result.append(my_temp_val)

print("结果是: " )
print(my_result)

print("排序后的列表是: ")
my_result.sort()
print(my_result)
输出结果
名单是:
['hi', 'hello', 'there', 'python', 'object', 'oriented', 'object', 'cool', 'language', 'py', 'extension',
'bjarne']
前缀是:
python
结果是:
[['hi', 'hello', 'there'], ['python', 'object', 'oriented', 'object', 'cool', 'language', 'py', 'extension',
'bjarne']]
排序后的列表是:
[['hi', 'hello', 'there'], ['python', 'object', 'oriented', 'object', 'cool', 'language', 'py', 'extension',
'bjarne']]

解释

  • 所需的包被导入到环境中。

  • 定义了一个字符串列表并显示在控制台上。

  • 前缀值已定义并显示在控制台上。

  • 定义了两个空列表。

  • 'zip_longest' 方法用于通过省略迭代中的第一个值来将列表与同一列表组合在一起。

  • 元素被附加到空列表之一。

  • 此列表显示为控制台上的输出。

  • 该列表再次排序并显示在控制台上。