Remove empty strings from a list of strings

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

    Depending on the size of your list, it may be most efficient if you use list.remove() rather than create a new list:

    l = ["1", "", "3", ""]
    
    while True:
      try:
        l.remove("")
      except ValueError:
        break
    

    This has the advantage of not creating a new list, but the disadvantage of having to search from the beginning each time, although unlike using while '' in l as proposed above, it only requires searching once per occurrence of '' (there is certainly a way to keep the best of both methods, but it is more complicated).

提交回复
热议问题