Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IndexError messages with python lists and split

I'm trying to learn python and delving 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.

This also works [0:6] and prints all the fields. [:1] prints the username also. [-1] also prints the last field.

The problem is that [1], [-2], [2], and so on result in this error

File "splits.py", line 16, in print fields[-2] IndexError: list index out of range

Am i doing something wrong here? I'm sure it's something silly but the examples i'm looking at say i can do [1], [2], and so on.

I don't think my input is messed up as it's /etc/passwd and [0] and [-1] work.

thanks much.

like image 456
anoopb Avatar asked Feb 02 '26 07:02

anoopb


1 Answers

Sounds like there are some empty lines in your file, maybe at the end.

Example:

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

You can fix it like this:

for line in lines:        
    line = line.rstrip()
    fields = line.split(':')
    if len(fields) == 1:
        continue
    print fields[0]
like image 173
Junuxx Avatar answered Feb 03 '26 20:02

Junuxx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!