Removing empty elements from an array in Python

with open("text.txt", 'r') as file: for line in file: line = line.rstrip('\n' + '').split(':') print(line) 

I'm having trouble deleting empty lists in a series of created arrays. I want to make each line an array in text.txt , so I will be able to accurately access each element individually for each line.

Empty lists are displayed as [''] - as you can see on the fourth line, I tried to explicitly exclude them. Empty elements were once filled with new string characters, they were successfully deleted with .rstrip('\n') .

Edit:

I had a misconception about some terminology, the above information was updated. Essentially, I want to get rid of empty lists.

+6
source share
1 answer

Since I do not see your exact string, it is difficult to give you a solution that meets your requirements, but if you want to get all the items in the list that are not empty strings, you can do this:

 >>> l = ["ch", '', '', 'e', '', 'e', 'se'] >>> [var for var in l if var] Out[4]: ['ch', 'e', 'e', 'se'] 

You can also use filter with None or bool :

 >>> filter(None, l) Out[5]: ['ch', 'e', 'e', 'se'] >>> filter(bool, l) Out[6]: ['ch', 'e', 'e', 'se'] 

If you want to get rid of lists with empty strings, then for your specific example you can do this:

 with open("text.txt", 'r') as file: for line in file: line = line.rstrip('\n' + '').split(':') # If line is just empty if line != ['']: print line 
+14
source

Source: https://habr.com/ru/post/957736/


All Articles