Remove empty strings from a list of strings

后端 未结 12 1742
孤城傲影
孤城傲影 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:07

    Instead of if x, I would use if X != '' in order to just eliminate empty strings. Like this:

    str_list = [x for x in str_list if x != '']
    

    This will preserve None data type within your list. Also, in case your list has integers and 0 is one among them, it will also be preserved.

    For example,

    str_list = [None, '', 0, "Hi", '', "Hello"]
    [x for x in str_list if x != '']
    [None, 0, "Hi", "Hello"]
    

提交回复
热议问题