如何在列表中去除所有字符串中的空格

7

我的列表是这样的:

mylist=[ " ","abc","bgt","llko","    ","hhyt","  ","      ","iuyt"]

如何移除列表中包含空格的所有字符串?

1
你所说的“空”是指包含仅为空格的字符串吗? - edsioufi
我的程序读取一个文件,将每一行分割开来,所以在列表中会有空字符串,也就是空格。 - no1
1
我不知道为什么没有人建议这个,但是以下代码似乎是所有答案中最快的 - [elem for elem in mylist if not elem.isspace()] - Sukrit Kalra
isspace()被支持了吗?我不知道... 谢谢你! - no1
10个回答

17
你可以使用列表推导式:list comprehension
 new_list = [elem for elem in mylist if elem.strip()]

strip() 保证了即使字符串只包含多个空格,也会被删除。


1
或者只需使用[elem for elem in mylist if elem.strip()] - Joachim Isaksson

9

使用filter和未绑定方法str.strip

Python 2.x

>>> mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
>>> filter(str.strip, mylist)
['abc', 'bgt', 'llko', 'hhyt', 'iuyt']

Python 3.x

>>> mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
>>> list(filter(str.strip, mylist))
['abc', 'bgt', 'llko', 'hhyt', 'iuyt']

4
只需使用过滤器和 None 参数即可。
filter(None, mylist)

如果“空字符串”指的是只包含空白字符的字符串,则应该使用以下代码:
filter(str.strip, mylist)

示例:

>>> filter(None, ['', 'abc', 'bgt', 'llko', '', 'hhyt', '', '', 'iuyt'])
['abc', 'bgt', 'llko', 'hhyt', 'iuyt']
>>> filter(str.strip, [' ', 'abc', 'bgt', 'llko', ' ', 'hhyt', ' ', ' ', 'iuyt'])
['abc', 'bgt', 'llko', 'hhyt', 'iuyt']

2
尝试使用filter(lambda x: x.strip(), mylist)
>>> mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
>>>
>>> filter(lambda x: x.strip(), mylist)
['abc', 'bgt', 'llko', 'hhyt', 'iuyt']
>>>
>>> mylist=[ " ","abc","bgt","llko","    ","hhyt","  ","      ","iuyt"]
>>>
>>> filter(lambda x: x.strip(), mylist)
['abc', 'bgt', 'llko', 'hhyt', 'iuyt']
>>>

2
mylist = [x for x in [ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"] if x]

使用“if”子句的列表推导,而在这种情况下,依赖于Python在布尔上下文中将空字符串(和空容器)视为“False”的事实。

如果您所说的“空”是指长度为零或仅包含空格,则可以将if子句更改为if x.strip()


1
我会这样做:

>>> mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
>>> new_list = [e for e in mylist if len(e.strip())!=0]
>>> new_list
      ['abc', 'bgt', 'llko', 'hhyt', 'iuyt']

1
该方法isalpha()检查字符串是否只包含字母字符:
mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"] 
mylist = [word for word in mylist if word.isalpha()]
print mylist

Output:['abc', 'bgt', 'llko', 'hhyt', 'iuyt']

0
mylist = [s for s in mylist if str is not " "]

0

0
>>> mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
>>> [i for i in mylist if i.strip() != '']
['abc', 'bgt', 'llko', 'hhyt', 'iuyt']

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接