How to remove empty string in a list?

前端 未结 9 1647
我在风中等你
我在风中等你 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:25

    I'll give you the answer to the question you should have asked -- how to avoid the empty string altogether. I assume you do something like this to get your list:

    >>> "He is so .... cool!".replace(".", "").split(" ")
    ['He', 'is', 'so', '', 'cool!']
    

    The point is that you use .split(" ") to split on space characters. However, if you leave out the argument to split, this happens:

    >>> "He is so .... cool!".replace(".", "").split()
    ['He', 'is', 'so', 'cool!']
    

    Quoth the docs:

    If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

    So you really don't need to bother with the other answers (except Blender's, which is a totally different approach), because split can do the job for you!

提交回复
热议问题