Home > Net >  How to remove empty strings from list
How to remove empty strings from list

Time:07-18

I want to remove empty strings from a list:

['""', 'live', '""', '""']

Using code:

list = [ele for ele in list if ele.strip()]
        print(list)

Output:

['""', 'live', '""', '""']

Wanted result:

['live']

CodePudding user response:

This is not empty string, it is '""', try this:

lst = ['""', 'live', '""', '""']
res = [ele for ele in lst if ele != '""']
print(res)

Update Check and remove empty string too -> ('')

lst = ['""', 'live', '""', '""', '', '']
res = [ele for ele in lst if not ele in ['""', '']]
print(res)

['live']

CodePudding user response:

None of the strings in your list are empty. Try this as input instead:

['', 'live', '']

Your code will give the correct output in this case.

If you also want to remove strings such as '""', you will have to adjust the if condition to do so.

CodePudding user response:

As Code-Apprentice mentioned, they are not empty values in your list but you can filter the list as follows:

sample_list = ['""', 'live', '""', '""']
sample_list = list(filter(('""').__ne__, sample_list))
  • Related