如何在 Python 中從字串列表中移除空字串?


在本文中,我們將瞭解如何在 Python 中從字串列表中移除空字串。

第一種方法是使用內建方法filter()。此方法接收字串列表作為輸入,移除空字串並返回更新後的列表。它將 None 作為第一個引數,因為我們試圖移除空空格,第二個引數是字串列表。

Python 內建函式filter()使您能夠處理可迭代物件並提取滿足指定條件的元素。此操作通常稱為過濾操作。您可以使用filter()函式將過濾函式應用於可迭代物件,並建立一個僅包含與給定條件匹配的元素的新可迭代物件。

示例

在下面給出的程式中,我們接收字串列表作為輸入,並使用 filter() 方法移除空空格,然後列印修改後的列表,該列表不包含空字串

str_list = ["Tutorialspoint","","Welcomes","","Everyone",""]

print("The given list of strings is")
print(str_list)

print("Removing the empty spaces")
updated_list = list(filter(None, str_list))
print(updated_list)

輸出

上面示例的輸出如下所示

The given list of strings is
['Tutorialspoint', '', 'Welcomes', '', 'Everyone', '']
Removing the empty spaces
['Tutorialspoint', 'Welcomes', 'Everyone']

使用 join() 和 split() 方法

第二種方法是使用join()split()方法。我們將接收字串列表,並使用 split() 方法以空格為分隔符將其拆分,然後使用 join() 方法將它們全部連線起來。

示例

在下面給出的示例中,我們接收字串列表作為輸入,並使用join()方法和split()方法移除空字串,然後列印修改後的列表,該列表不包含空字串

str_list = ["Tutorialspoint","","Welcomes","","Everyone",""]

print("The given list of strings is")
print(str_list)

print("Removing the empty spaces")
updated_list = ' '.join(str_list).split()
print(updated_list)

輸出

上面示例的輸出如下所示

The given list of strings is
['Tutorialspoint', '', 'Welcomes', '', 'Everyone', '']
Removing the empty spaces
['Tutorialspoint', 'Welcomes', 'Everyone']

使用 remove() 方法

第三種方法是蠻力方法,即透過迭代列表,然後檢查每個元素是否為空字串。如果字串為空,則使用列表的remove()方法將其從列表中移除,否則,我們繼續處理下一個字串。

示例

在下面給出的示例中,我們接收字串列表作為輸入,並使用remove()方法和迴圈移除空字串,然後列印修改後的列表,該列表不包含空字串。

str_list = ["Tutorialspoint","","Welcomes","","Everyone",""]
print("The given list of strings is")
print(str_list)

print("Removing the empty spaces")
while ("" in str_list):
   str_list.remove("")
print(str_list)

輸出

上面示例的輸出如下所示

The given list of strings is
['Tutorialspoint', '', 'Welcomes', '', 'Everyone', '']
Removing the empty spaces
['Tutorialspoint', 'Welcomes', 'Everyone']

更新於: 2022-12-07

8K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.