0

So if I have a given information line and I'm trying to index each line but the way they overlap prevents generalizing indexes (first line being 123 3455 then the second line being 1234567 12) how can I categorize the first two numbers with the same name holder?

ie:

fo = open file
for line in fo:
    first_number = line[0:3]

this doesn't work because for the second line the number is a lot longer, but how would I index the numbers to the white space after the first number?

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
Gideon
  • 1
  • 5
  • Possible duplicate of [Split string on whitespace in Python](http://stackoverflow.com/questions/8113782/split-string-on-whitespace-in-python) – Lev Levitsky Mar 20 '16 at 19:55
  • you should split the lines `line_list = line.split()` and get `first_number = line_list[0]` – dnit13 Mar 20 '16 at 19:56
  • Thank you @dnit13 this was just what I was looking for! – Gideon Mar 20 '16 at 19:59
  • @Gideon on SO you must select one of the answers and mark it as good answer. you can also give points to comments and answers. – DevLounge Mar 20 '16 at 21:03

2 Answers2

1
with open(file, 'r') as fo:
    for line in fo:
        first_number, second_number = line.strip().split()
        # do something else with these 2 variables
        ...

str.split(separator=' ') will return a tuple as you have 2 numbers separated by a space on your lines. I strip the line to remove the \n.

What you see here is like a tuple assignment:

(a, b) = (1, 2)

which can be simplified as such:

a, b = 1, 2

And if you don't care about the second number you can write (common practice):

first_number, _ = line.split()
DevLounge
  • 8,313
  • 3
  • 31
  • 44
1

If they are always separated by a space then you could replace line[0:3] with line.partition(' ')[0]

aspotic
  • 76
  • 4