【问题标题】:Python - TypeError: string indices must be integers [closed]Python - TypeError:字符串索引必须是整数[关闭]
【发布时间】:2014-02-15 17:21:02
【问题描述】:

由于某种原因,这段脚本返回错误:“TypeError: string indices must be integers”;我看不出有什么问题。我是不是很愚蠢并且在这里忽略了一个明显的错误?我一辈子都见不到!

terms = {"ALU":"Arithmetic Logic Unit"}
term = input("Type in a term you wish to see: ")

if term in terms:
    definition = term[terms]
    sentence = term + " - " + definition
    print(sentence)
else:
    print("Term doesn't exist.")

【问题讨论】:

  • 天哪,我是不是觉得自己很蠢!感谢大家为我指明正确的方向。

标签: python typeerror


【解决方案1】:

我想你想要这样:definition = terms[term]

【讨论】:

    【解决方案2】:

    这行definition = term[terms] 试图从字符串term 中取出一个字符。你可能只是打错了,想要

    definition = terms[term]
                     ^ here, reference the dict, not the string
    

    【讨论】:

      【解决方案3】:

      您正在索引字符串 term 而不是字典 terms。试试:

      definition = terms[term]
      

      【讨论】:

        【解决方案4】:

        您不小心交换了变量。改变这个:

        definition = term[terms]
        

        到这里:

        definition = terms[term]
        

        【讨论】:

          猜你喜欢
          • 2021-05-04
          • 2016-03-26
          • 2016-02-17
          • 2023-03-03
          • 1970-01-01
          • 2022-11-02
          • 2019-04-26
          • 2020-08-04
          • 1970-01-01
          相关资源
          最近更新 更多