Remove empty strings from a list of strings

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

    I would use filter:

    str_list = filter(None, str_list)
    str_list = filter(bool, str_list)
    str_list = filter(len, str_list)
    str_list = filter(lambda item: item, str_list)
    

    Python 3 returns an iterator from filter, so should be wrapped in a call to list()

    str_list = list(filter(None, str_list))
    

提交回复
热议问题