How to remove empty string in a list?

前端 未结 9 1639
我在风中等你
我在风中等你 2020-12-28 17:42

For example I have a sentence

\"He is so .... cool!\"

Then I remove all the punctuation and make it in a list.

[\"He\", \"         


        
9条回答
  •  無奈伤痛
    2020-12-28 18:17

    You can use filter, with None as the key function, which filters out all elements which are Falseish (including empty strings)

    >>> lst = ["He", "is", "so", "", "cool"]
    >>> filter(None, lst)
    ['He', 'is', 'so', 'cool']
    

    Note however, that filter returns a list in Python 2, but a generator in Python 3. You will need to convert it into a list in Python 3, or use the list comprehension solution.

    Falseish values include:

    False
    None
    0
    ''
    []
    ()
    # and all other empty containers
    

提交回复
热议问题