Siyah Siyah - 4 months ago 34
Python Question

How to get rid of empty strings in Python when splitting a list?

Newbie with a question here. I have an input file which consists of these lines:

['Some Name__________2.0 2.0 1.3\n', 'Some Name__________1.0 9.0 1.0\n', # and so on....]

I've formatted it with
, to this:

['Some Name', '', '', '', '2.0 2.0 1.3\n']
['Another Name', '', '', '', '1.0 9.0 1.0\n']
['Another Name', '', '', '', '1.0 9.0 1.0\n']
# and so on

What I wanted to do, is to get the names beneath each other, while I am getting rid of the _ signs.

This is my code:

def openFile():
fileFolder = open('TEXTFILE', 'r')
readMyFile = fileFolder.readlines()

for line in readFile:
line = line.split("_")

personNames = line[0]

print personNames

print openFile()

So what I get now, is:

Some Name
Another Name
Another Name

That is cool, but I want to go further and that is where I am getting stuck. What I want to do now, is to get rid of the empty strings (
) and print the numbers you can see, just beside the names I've already formatted

I thought that I could just do this:

for line in readFile:
line = line.split("_")
get_rid_of_spaces = line.split() #getting rid of spaces too

personNames = line[0]

But this gives me this error:

AttributeError: 'list' object has no attribute 'split'

Can someone please give me some directions on how to do this? I want to learn this.

I also tried incrementing the index number, but this failed and I read it's not the best way to do this, so now I am going this way. Hope that someone can help me and give me tips and hints.

Beside that, I'd expect that when I'd do
, that it would give me the empty strings, but it doesn't...

What am I missing here?

readfile=['Some name____2.0 2.1 1.3','Some other name_____2.2 3.4 1.1']

for line in readfile:
    first_split=list(part for part in line.split('_') if part!='')
    data.append(list([first_split [0],first_split [1].split(' ')]))


I think this does what you wanted if I understood you correctly. It prints out:

[['Some name', ['2.0', '2.1', '1.3']], ['Some other name', ['2.2', '3.4', '1.1']]]