python - 字符串索引超出 Python 范围

标签 python types int

目前正在尝试编写一个代码,主要测试位于 r 的字母(所以这里是 (2,3))是否等于特定字母或字符串。

def test():

txt = "test.txt"
r = (2,3)
if txt[r[0]][r[1]] == 'l':
    return (True)
elif txt[r[0]][c[1]] == "m":
    return (False)
elif txt[r[0]][c[1]] == "b":
    return (True)

但我一直收到错误。错误对话是这样的:

if txt[r[0]][r[1]] == 'l':
IndexError: string index out of range

考虑到我今天早些时候让它工作,我不知道我做错了什么。 另外,在你问之前,我必须出于特定原因以这种方式编码。

谢谢。

最佳答案

请注意,

if txt[r[0]][r[1]] == 'l':

应该写成

if txt[r[0]:r[1]] == 'l':

和类似的其他用法应该改变

关于python - 字符串索引超出 Python 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9920800/

相关文章:

python - 使用 pip3 : module "importlib._bootstrap" has no attribute "SourceFileLoader"

python - Flask框架可以将实时数据从服务器发送到客户端浏览器吗?

python - 用于同步训练和验证的可重新初始化迭代器

Java Generics Silly Thing(为什么我不能推断类型?)

c++ - 比较 (int)double 和 (int)int 时出现异常

python - 使用正则表达式重新标记并删除字符串中的冗余项

r - 在与 R 交互的数据库中处理字段类型

haskell - do block 中的返回类型

java - Java 中的 16 位桶式移位

C:字符串例如 "abcde123"到 int 123