I am trying to learn python and delve into string functions. As a simple example, I wrote this
FILENAME = "/etc/passwd"
filehandle = open(FILENAME, 'r')
lines = filehandle.readlines()
for line in lines:
line = line.rstrip()
fields = line.split(':')
print fields[0]
This example works every time and gives me a username. The first field in the list.
It also works [0: 6] and prints all fields. [: 1] also prints the username. [-1] also prints the last field.
The problem is that [1], [-2], [2] etc. lead to this error
File "splits.py", line 16, in print fields [-2] IndexError: index index out of range
Am I doing something wrong here? I am sure this is something stupid, but the examples I look at can do [1], [2] etc.
I don’t think my input is corrupted since it / etc / passwd and [0] and [-1] work.
Many thanks.
source
share