Remove empty strings from a list of strings

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

    Use filter:

    newlist=filter(lambda x: len(x)>0, oldlist) 
    

    The drawbacks of using filter as pointed out is that it is slower than alternatives; also, lambda is usually costly.

    Or you can go for the simplest and the most iterative of all:

    # I am assuming listtext is the original list containing (possibly) empty items
    for item in listtext:
        if item:
            newlist.append(str(item))
    # You can remove str() based on the content of your original list
    

    this is the most intuitive of the methods and does it in decent time.

提交回复
热议问题