Siyah Siyah - 16 days ago 9
Python Question

Why can't I remove the empty string in this list?

I know this is a rather trivial question, but that's why I thought too when I was trying to solve it. Yet, I am here and asking this question. It should be very easy and probably I am doing something completely wrong, but I'd like to know what I am doing wrong.

I have this list of strings:

['1', ' ', '2', ' ', '6', ' ', '6', ' ', '5', ' ', '6', ' ', '5']


I've stripped the /n already by doing this:

rstrip("\n")


And now, I want to get rid of the empty strings, so I tried to use
filter(None,x)
, but this isn't working. Also, tried to remove it with a
for loop
; also didn't work.

filter(None, the_list)


What is wrong with this statement? I also tried this wrapping it into
list()
, but didn't work either.

Also tried this:

my_list = [str for str in the_list if str]


Am I missing something?

PS: my ultimate goal is to convert the strings into ints so that I can calculate stuff, but I can only that if I get rid of the empty strings.

Answer

You don't have empty strings. You have strings with one space in each.

You can remove those by testing if they are empty after stripping:

my_list = [el for el in the_list if el.strip()]

However, you may want to examine how you got that list in the first place. Perhaps you can strip out those spaces earlier, or use str.split() without an argument to split on arbitrary width whitespace rather than on a fixed-width string.