Siyah Siyah - 3 months ago 15
Python Question

Why can't I convert the list that I fetched with readlines(), to floats?

I've opened a new file via my IDE and turned it into a list via readlines. Why? Because I want to print them underneath each other. When I use

, it just prints one item, while I need the whole list to be printed.

The actual file:

['Some name__________1.5 6.5 6.5\n', 'Another name________6.3 1.2 1.5\n']

Right now, I have managed to fetch the last part of the list which looks likes this:

1.5 3.5 4.5
2.5 3.5 4.5
5.5 3.5 4.5

What I want to do now, is to calculate the average of these numbers, but: Python does not recognize them as numbers (ints, floats) at all.

When I'd use
, it doesn't show the type of it. Therefore, I don't think they are ints, strings or floats.

What I think I need to do, is to convert the items in this list, into floats, because they are supposed to be floats. But to do so, I need to know what I am doing wrong and how I could fix that.

This is my code:

def zopenFile():
fileFolder = open('TEXTFILE', 'r')

readFile = fileFolder.readlines()

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

grades = line[-1]

print grades


I tried doing
grades = map(float,line[-1])

But in that case, the console says:
could not convert string to float: .

The weird part is, that if I would use
, it wouldn't say it has the type of a string in the console. I am confused right now... is it a string? Is it a float already? If so, why can't I just map it into a float?

Can someone point me in the right direction please?

And I know I can use
, but I don't want to. Can someone show me how to do it with


Your map is operating on each character of the string, because when you iterate over a string you get individual characters. You want to use another split to get each number into separate strings.

grades = map(float, line[-1].split())