My list is like this,
mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
How to remove all spaces containing strings inside this list?
My list is like this,
mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
How to remove all spaces containing strings inside this list?
You could use a list comprehension:
new_list = [elem for elem in mylist if elem.strip()]
Using strip()
guarantees that even strings containing only multiple spaces will be removed.
Use filter
with unbound method str.strip
.
>>> 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']
Just use filter with None
.
filter(None, mylist)
If by empty strings you mean strings containing only whitespace characters, then you should use:
filter(str.strip, mylist)
Examples:
>>> 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']
Try to use 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]
... List comprehension with "if" clause and, in this case, relying on the fact that Python considers empty strings (and empty containers) to be "False" in boolean contexts.
If by "empty" you mean zero-length or containing only spaces then you can change the if
clause to read if x.strip()
I would do it this way:
>>> 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']
The method isalpha() checks whether the string consists of alphabetic characters only:
mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
mylist = [word for word in mylist if word.isalpha()]
print mylist
Output:['abc', 'bgt', 'llko', 'hhyt', 'iuyt']
list = ["first", "", "second"]
[x for x in list if x]
Output: ['first', 'second']
Shortened as suggested,the same question given below
>>> mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
>>> [i for i in mylist if i.strip() != '']
['abc', 'bgt', 'llko', 'hhyt', 'iuyt']