Python 如何从字符串列表中删除空字符串

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']

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程