Remove empty strings from a list of strings

后端 未结 12 1684
孤城傲影
孤城傲影 2020-11-22 04:33

I want to remove all empty strings from a list of strings in python.

My idea looks like this:

while \'\' in str_list:
    str_list.remove(\'\')
         


        
12条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 05:28

    For a list with a combination of spaces and empty values, use simple list comprehension -

    >>> s = ['I', 'am', 'a', '', 'great', ' ', '', '  ', 'person', '!!', 'Do', 'you', 'think', 'its', 'a', '', 'a', '', 'joke', '', ' ', '', '?', '', '', '', '?']
    

    So, you can see, this list has a combination of spaces and null elements. Using the snippet -

    >>> d = [x for x in s if x.strip()]
    >>> d
    >>> d = ['I', 'am', 'a', 'great', 'person', '!!', 'Do', 'you', 'think', 'its', 'a', 'a', 'joke', '?', '?']
    

提交回复
热议问题