Siyah Siyah - 1 year ago 74
Python Question

How to get the last part of a list containing floats, strings and special characters in Python when splitting?

I need to get the last part of a list that I have fetched with

. This is a part of the string / list:

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

I solely want to get the numbers and ignore the rest of them, but how do I do that? So I want this:

2.0 2.0 1.3

To get the name part, I know I need to use
and use an index to fetch it...

When I try getting the numbers, though, I fail, because it just outputs nothing in the console.

This is the code that gets the names:

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

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

personNames = line[0]

print personNames

print openFile()

I thought that using
would be sufficient to get the numbers as well, but it isn't. Can someone explain to me why that is not working and how I could get it to work, while using my style of code instead of importing stuff?

Is there something like a range or something that could say to split() just to get the last part of it?

Answer Source

Based on your last question, you haven't gotten rid of those empty strings in this solution yet. So line[2] and line[3] didn't work because they're probably empty strings that are '_'s originally: readFile = ['Some name____2.0 2.1 1.3','Some other name_____2.2 3.4 1.1']

Here's how I would do it:

def openFile():
    readFile = ['Some name____2.0 2.1 1.3\n','Some other name_____2.2 3.4 1.1\n']


    for line in readFile:
        line = (line.rstrip()).split("_") #EDIT: Strip the newline character in this line
        data.append(line [-1].split(' '))


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download