Skip to main content
 首页 » 编程设计

python之如何删除字符串列表中的所有空白元素

2024年11月24日27cmt

我有一个字符串列表,text= ['He', 'was', '' ,'sitting', ' ', 'next', ' ', 'to me']

我想从列表中删除 whitespace 元素 ' '。

我试过使用 filter 方法,但它只会删除空元素,

list(filter(None, text)) 

我希望列表是这样的

['He', 'was' ,'sitting','next','to me'] 

请您参考如下方法:

现在,正如您正确指出的那样,list(filter(None, text)) 正在删除空字符串,而不是带空格的字符串

要删除带有空格的字符串,您可以 strip列表中每个元素的空格并进行比较,然后用非空字符串创建一个新列表

text= ['He', 'was', '' ,'sitting', ' ', 'next', ' ', 'to me'] 
 
print([item for item in text if item.strip()]) 
 
#Or using filter 
#print(list(filter(lambda item:item.strip(), text))) 

输出将是

['He', 'was', 'sitting', 'next', 'to me']