我的清单是这样的
mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
如何删除此列表中包含字符串的所有空格?
>>> mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
>>> filter(str.strip, mylist)
['abc', 'bgt', 'llko', 'hhyt', 'iuyt']
>>> mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
>>> list(filter(str.strip, mylist))
['abc', 'bgt', 'llko', 'hhyt', 'iuyt']
只需将过滤器与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']
尝试使用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']
>>>
mylist = [x for x in [ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"] if x]
... 使用“if”子句列出理解,在这种情况下,依赖于 Python 认为空字符串(和空容器)在布尔上下文中为“假”的事实。
如果“空”是指零长度或仅包含空格,则可以将if
子句更改为if x.strip()
我会这样做:
>>> 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']
isalpha() 方法检查字符串是否仅由字母字符组成:
mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
mylist = [word for word in mylist if word.isalpha()]
print mylist
Output:['abc', 'bgt', 'llko', 'hhyt', 'iuyt']
mylist = [s for s in mylist if str is not " "]
>>> mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
>>> [i for i in mylist if i.strip() != '']
['abc', 'bgt', 'llko', 'hhyt', 'iuyt']