IndexError posts with python and split lists

I am trying to learn python and delve into string functions. As a simple example, I wrote this

# example line
# username:*:231:-2:gecos field:/home/dir:/usr/bin/false

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.

+3
source share
1

, , , .

:

>>>line = ''
>>>fields = line.split(":")
>>>print fields[0]
''
>>>print fields[-1]
''
>>>print fields[0:6]
''
>>>print fields[1]
IndexError: list index out of range

:

for line in lines:        
    line = line.rstrip()
    fields = line.split(':')
    if len(fields) == 1:
        continue
    print fields[0]
+1

All Articles