【问题标题】:string index out of range & encoding utf-8 (python3)字符串索引超出范围 & 编码 utf-8 (python3)
【发布时间】:2015-07-06 11:20:51
【问题描述】:

我总是收到这个错误...

Traceback (most recent call last):
File "C:/Users/01/Desktop 3/Projects/univ/number.py", line 11, in <module>
print(line[5])
IndexError: string index out of range

我只想从 txt 文件中读取信息

readFile = open("utf.txt", encoding="utf-8").read()
for line in readFile:
print(line[5])

我将txt编码设置为“utf-8”,我的IDE也有相同的编码集 还有一件事要考虑:文件是用俄语编写的

【问题讨论】:

    标签: python-3.x encoding utf-8 text-files


    【解决方案1】:

    您的readFile 变量是一个字符串(因为.read() 方法)。当你迭代它时,你会得到一个字符(这是你的 line 变量)。然后你尝试打印这个字符的第六个元素。当然你会得到IndexError

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-13
      • 1970-01-01
      • 1970-01-01
      • 2016-02-19
      • 2012-03-02
      • 2016-02-10
      • 2021-01-30
      相关资源
      最近更新 更多