Remove empty strings from a list of strings

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

    Keep in mind that if you want to keep the white spaces within a string, you may remove them unintentionally using some approaches. If you have this list

    ['hello world', ' ', '', 'hello'] what you may want ['hello world','hello']

    first trim the list to convert any type of white space to empty string:

    space_to_empty = [x.strip() for x in _text_list]
    

    then remove empty string from them list

    space_clean_list = [x for x in space_to_empty if x]
    

提交回复
热议问题