Skip to content Skip to sidebar Skip to footer

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 =

Solution 1:

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]

Post a Comment for "Indexerror Messages With Python Lists And Split"