带有 python 列表和拆分的 IndexError 消息 [英] IndexError messages with python lists and split
问题描述
我正在尝试学习 Python 并深入研究字符串函数.作为一个简单的例子,我写了这个
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.
这也适用于 [0:6] 并打印所有字段.[:1] 也打印用户名.[-1] 还打印最后一个字段.
This also works [0:6] and prints all the fields. [:1] prints the username also. [-1] also prints the last field.
问题是[1]、[-2]、[2]等导致这个错误
The problem is that [1], [-2], [2], and so on result in this error
文件splits.py",第 16 行,在打印字段[-2]IndexError:列表索引超出范围
我在这里做错了吗?我确定这很愚蠢,但我正在查看的示例说我可以做 [1]、[2] 等等.
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.
我不认为我的输入搞砸了,因为它是/etc/passwd 和 [0] 和 [-1] 工作.
I don't think my input is messed up as it's /etc/passwd and [0] and [-1] work.
非常感谢.
推荐答案
听起来您的文件中有一些空行,可能在末尾.
Sounds like there are some empty lines in your file, maybe at the end.
示例:
>>>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]
这篇关于带有 python 列表和拆分的 IndexError 消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!