关于python:如何删除列表中字符串中的所有空格

How to remove all spaces in the strings in list

我的名单是这样的,

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

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


您可以使用列表理解:

1
 new_list = [elem for elem in mylist if elem.strip()]

使用strip()可以保证即使只包含多个空格的字符串也将被删除。


使用filter与未绑定方法str.strip结合使用。

Python 2 x

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

Python 3 x

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


只需使用带None的过滤器。

1
filter(None, mylist)

如果空字符串是指只包含空格字符的字符串,则应使用:

1
filter(str.strip, mylist)

实例:

1
2
3
4
>>> 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']

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

…使用"if"子句列出理解,在这种情况下,依赖于这样一个事实:在布尔上下文中,Python认为空字符串(和空容器)是"false"。

如果"空"的意思是零长度或只包含空格,则可以将if子句改为读if x.strip()


尽量使用filter(lambda x: x.strip(), mylist)

1
2
3
4
5
6
7
8
9
10
>>> 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']
>>>

方法isalpha()检查字符串是否仅由字母字符组成:

1
2
3
4
5
mylist=["","abc","bgt","llko","","hhyt","","","iuyt"]
mylist = [word for word in mylist if word.isalpha()]
print mylist

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


我会这样做:

1
2
3
4
>>> 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
2
3
>>> mylist=["","abc","bgt","llko","","hhyt","","","iuyt"]
>>> [i for i in mylist if i.strip() != '']
['abc', 'bgt', 'llko', 'hhyt', 'iuyt']

1
2
list = ["first","","second"]
[x for x in list if x]

输出:''first'、'second']

按建议缩短,下面给出相同的问题

从字符串列表中删除空字符串


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