简体   繁体   English

Python错误:“ IndexError:字符串索引超出范围”

[英]Python error:“IndexError: string index out of range”

I import my txt file as str by using with open 我通过使用open将txt文件导入为str

with open('./doc', 'r') as f:
dat = f.readlines()

then I want to clean the data by using a for loop 然后我想使用for循环清除数据

docs = []
for i in dat:
if i.strip()[0] != '<':
    docs.append(i)

error returns 错误返回

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-131-92a67082e677> in <module>()
      1 docs = []
      2 for i in dat:
----> 3     if i.strip()[0] != '<':
      4         docs.append(i)

IndexError: string index out of range

but if I change the code like this,just select the first 3000 lines, the code works. 但是,如果我这样更改代码,只需选择前3000行,代码就可以工作。

docs = []
for i in dat[:3000]:
if i.strip()[0] != '<':
    docs.append(i)

My txt file contains 93408 lines ,why I can't select them all? 我的txt文件包含93408行,为什么我不能全部选择它们? thx! 谢谢!

one or more lines could be empty, you need to check it before take first elem 一行或多行可能是空的,您需要先进行检查,然后再进行第一个元素

if i.strip() != "" and i.strip()[0] != '<':
    docs.append(i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM