Python - 選擇性連續後綴連線


當必須查詢選擇性連續後綴連線時,可以使用簡單的迭代、“endswith”方法和“append”方法。

示例

下面是相應演示

my_list = ["Python-", "fun", "to-", "code"]

print("The list is :")
print(my_list)

suffix = '-'
print("The suffix is :")
print(suffix)

result = []
temp = []
for element in my_list:
   temp.append(element)

   if not element.endswith(suffix):
      result.append(''.join(temp))
      temp = []

print("The result is :")
print(result)

輸出

The list is :
['Python-', 'fun', 'to-', 'code']
The suffix is :
-
The result is :
['Python-fun', 'to-code']

說明

  • 定義了一個字串列表並將其顯示在控制檯上。
  • 定義了一個字尾值並將其顯示在控制檯上。
  • 建立兩個空列表。
  • 對列表進行迭代,並將元素追加到空列表中。
  • 如果元素未以特定字尾結尾,則使用“join”方法將其追加到空列表中。
  • 再次清空另一個列表。
  • 將其作為輸出顯示在控制檯上。

更新於: 2021 年 9 月 16 日

93 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.