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']
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']
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.
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))
('""').__ne__ is very... iffy, even though it might be tempting to not use a lambda. Still, maybe lambda e: e != '""' ? However, neither will remove actual empty strings...
ifcondition to check for strings with double quotes, too.