Remove empty strings from a list of strings

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

    Using a list comprehension is the most Pythonic way:

    >>> strings = ["first", "", "second"]
    >>> [x for x in strings if x]
    ['first', 'second']
    

    If the list must be modified in-place, because there are other references which must see the updated data, then use a slice assignment:

    strings[:] = [x for x in strings if x]
    

提交回复
热议问题