If I loop through the list like this:
print(b)
for i in list:
if i == '':
b.remove(i)
print(b)
The empty strings remain in the output:
['','123','','','','','1','','1232','']
['123','1','','1232','']
How can I remove them all?
If I loop through the list like this:
print(b)
for i in list:
if i == '':
b.remove(i)
print(b)
The empty strings remain in the output:
['','123','','','','','1','','1232','']
['123','1','','1232','']
How can I remove them all?
I guess you should not remove while iterating through the list. Try
b = list(filter(None, b))
or
b = [s for s in b if not b == '']
or
for i in range( len(b) - 1, -1, -1) :
if i == '':
b.del(i)
The first and second are more functional solutions,
and the third iterates through the list in reverse.
I think axolotl's answer is correct, but you can use this for solving your problem too:
a = 'a123aaaaa1aa1232a'
b = a.split('a')
lst = []
for i in b:
if i != '':
lst.append(i)
print(lst)
Note for being better programmer: Don't name your variables something easy like a
and b
, instead, use a name that make sense with your variable!