-1
date = line[4:5]

I want the 3rd and 4th values in the line to be stored as date. When I use the code above, I end up with date = 1, when I want it to be equal to an integer between 00 and 99. How can I do this right

Anders157
  • 13
  • 1
  • 1
  • 3
  • Probably what you want is `line[2:4]` (3rd and 4th characters), but it's hard to say. Can you give us an example? – Andrea Corbellini May 09 '15 at 08:47
  • "732919 20060831 10 1 38 25 -1 20" That's line 1. The first 2 numbers (the long ones) indicate date. I'd like to store the "19" as date. Or I mean, storing "732919" or "20060831" would be equally useful. – Anders157 May 09 '15 at 08:48
  • You'll have to show us what kind of lines you have, and what your expected output is. You may be getting confused as to what slicing does; you are selecting *individual characters*, not delimited values. – Martijn Pieters May 09 '15 at 08:48
  • 2
    @Anders157: sounds like you wanted [Split string into a list in Python](http://stackoverflow.com/q/743806) – Martijn Pieters May 09 '15 at 08:49

1 Answers1

1

Try this:

date = int(line[2:4])

There are two things here:

  • Python is 0-indexed, i.e. the third element is '2'
  • Slicing an array does not include the last element. Here you get the values at index positions 2 and 3 but not 4.
  • int() converts your string '31' into the integer 31.

I'd have a look at Python's datetime utils.

Unapiedra
  • 15,037
  • 12
  • 64
  • 93
  • wow, thanks so much. sorry about the index confusion, i said 3rd/4th when i meant 5th/6th. Didn't know that about slicing. This is my first time using python so its strange. really appreciate it, along with the other comments on my question. apologies for being so confusing/bad at this – Anders157 May 09 '15 at 08:54