简体   繁体   English

在 Python 中索引字符串时出现问题

[英]Trouble with indexing a string in Python

I am trying to check the first character in each line from a separate data file.我试图从一个单独的数据文件中检查每行中的第一个字符。 This is the loop that I am using, but for some reason I get an error that says string index out of range.这是我正在使用的循环,但由于某种原因,我收到一条错误消息,指出字符串索引超出范围。

for line_no in length:
  line_being_checked = linecache.getline(file_path, line_no)

  print(line_being_checked[0]) 

From what I understand (not very in english), lenght is the number of lines you want to check in the files.据我了解(英语不是很好), lenght是您要检查文件的行数。 You could do something like that:你可以这样做:

for line in open("file.txt", "r").read().splitlines():
        print(line[0])

This way, you'll be sure that the lenght is correct.这样,您就可以确定长度是正确的。

For the error, it is possible that you have an empty line, so you could len(line) to check if it is the case.对于错误,您可能有一个空行,因此您可以len(line)检查是否是这种情况。

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

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