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

时间:2013-08-29 09:06:05

标签: python

我的清单是这样的,

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

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

10 个答案:

答案 0 :(得分:10)

您可以使用list comprehension

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

使用strip()可以保证甚至只删除包含多个空格的字符串。

答案 1 :(得分:7)

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

答案 2 :(得分: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']

答案 3 :(得分: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']
>>>

答案 4 :(得分:2)

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

...使用“if”子句列出理解,在这种情况下,依赖于Python认为空字符串(和空容器)在布尔上下文中为“False”这一事实。

如果“空”表示零长度或仅包含空格,则可以将if子句更改为if x.strip()

答案 5 :(得分: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']

答案 6 :(得分: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']

答案 7 :(得分:0)

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

答案 8 :(得分:0)

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

输出:['first','second']

按照建议缩短,下面给出了同样的问题

Remove empty strings from a list of strings

答案 9 :(得分:0)

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