I have a list with multiple, consecutive empty (''
) elements. I wish to remove all but one of the empty elements in a series of consecutive empty elements. Let me illustrate:
I have the following test data:
test_data = ['hello', '', '', '', 'this is it', '', 'the one', '', '', '', '', 'img', 'out there', 'when']
That I wish to clean up to get this:
test_data = ['hello', '', 'this is it', '', 'the one', '', 'img', 'out there', 'when']
Notice that in the above list, there is not more than one empty element between elements in the list.
I wrote the following code, but this leaves two empty elements:
output = []
newline_count = 0
for element in test_data:
if element.strip() != '': output.append(element)
else:
newline_count += 1
if newline_count < 2: output.append('')
else: newline_count = 0
print(output)
Where am I going wrong?