如何在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']
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP