简体   繁体   中英

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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