0

I have thousands of lines with data in the form: 6580,f|S,17:42:29.3,-39:01:48,2.19,2.41,-0.22

I would like to take only the last number (in this case -0.22) so I can perform some calculations. My problem is: the lines aren't strings, and they have variable length (slicing from the beginning/end isn't an option). How can separate those commas and create a list of strings or floats?

Is there a way to separate that sequence in way that I can use, for example, "line[6]" to get that last value?

Germano
  • 125
  • 2
  • 6

2 Answers2

0

If the floating number you need is always the last entry in comma-separated line, float(line.split(',')[-1]) should do the trick.

Otherwise I would do something like the following:

def isFloat(val):
    try:
        float(val)
        return True
    except ValueError:
        return False

 number = [x for x in line.split(',') if isFloat(x)][-1]

If all the lines you have are stored in a text file, open it and process your lines:

with open("my_file.txt") as f:
    for line in f:
        # Here goes the code where you're getting the floating number from the line 
aga
  • 27,954
  • 13
  • 86
  • 121
  • Using float(line.split(',')) solved the issue, and then I only needed a line[6] to take the last value. Thank you! – Germano Dec 06 '13 at 17:24
-1

Maybe you're looking for this syntax line[:-1] will always give you the last element in an array.

It could possibly be line[::-1]. Somebody should correct me if I'm wrong.

BTW if they are not strings, what are they?


Edit. It's line[-1], Getting the last element of a list in Python

Community
  • 1
  • 1
Anton
  • 2,282
  • 26
  • 43