如何从Python字符串列表中删除空字符串?
在本文中,我们将找出如何从Python字符串列表中删除空字符串。
第一种方法是使用内置方法 filter() 。此方法从字符串列表中获取输入并删除空字符串,并返回更新后的列表。它将None作为第一个参数,因为我们正在尝试删除空格,下一个参数是字符串列表。
内置Python函数 filter() 使您可以处理可迭代的对象并提取满足指定条件的元素。该操作通常称为过滤操作。您可以使用 filter() 函数将过滤函数应用于可迭代对象,并创建仅包含与给定条件匹配的元素的新可迭代对象。
阅读更多:Python 教程
示例
在下面给出的程序中,我们以字符串列表作为输入,使用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']