简体   繁体   English

我收到此错误-> TypeError:字符串索引必须为整数

[英]I'm getting this error --> TypeError: string indices must be integers

I'm trying to learn object oriented programming by making a text based rpg which is shown below. 我试图通过制作基于文本的rpg来学习面向对象的编程,如下所示。 The parts of it that are related to my question are: 与我的问题有关的部分是:

    def equipArmor(self):
        for armor in self.armorsOwned:
            select = 1
            if self.armor == armor:
                print(str(select) + ". " + str(armor["Name"]) + " (Equipped)")
            else:
                print(str(select) + ". " + str(armor["Name"]))
            select += 1
        armor_choice = input("Type the name of the armor you would like to equip\n")
        for i in self.armorsOwned:
            if armor_choice == i["Name"]:
                if self.armor == i:
                    print("You already have that equipped")
                else:
                    self.armor = i["Name"]
                    print("You equipped the {}".format(i["Name"]))
                    self.maxhp += i["Effect"]

and: 和:

class Shop:

    armors = {"BronzeArmor":{"Name": "Bronze armor",
                             "Cost": 30,
                             "Effect": 10},
              "SilverArmor":{"Name": "Silver armor",
                             "Cost": 75,
                             "Effect": 20}}

Here is the rest just so you can understand the context of my code: 这是剩下的,以便您可以了解我的代码的上下文:

import time
import sys

class Player:

    def __init__(self):
        self.level = 1
        self.exp = 0
        self.gold = 0
        self.maxhp = 20
        self.hp = self.maxhp
        self.attack = 1
        self.weapon = ""
        self.armor = ""
        self.weaponsOwned = {}
        self.armorsOwned = {}

    def checkHp(self):
        self.hp = max(0, min(self.hp, self.maxhp))

    def deadCheck(self):
        if self.hp == 0:
            print("You died!")
            sys.exit()

    def equipArmor(self):
        for armor in self.armorsOwned:
            select = 1
            if self.armor == armor:
                print(str(select) + ". " + str(armor["Name"]) + " (Equipped)")
            else:
                print(str(select) + ". " + str(armor["Name"]))
            select += 1
        armor_choice = input("Type the name of the armor you would like to equip\n")
        for i in self.armorsOwned:
            if armor_choice == i["Name"]:
                if self.armor == i:
                    print("You already have that equipped")
                else:
                    self.armor = i["Name"]
                    print("You equipped the {}".format(i["Name"]))
                    self.maxhp += i["Effect"]

class Enemy:

    def __init__(self, attack, maxhp, exp, gold):
        self.exp = exp
        self.gold = gold
        self.maxhp = maxhp
        self.hp = maxhp
        self.attack = attack

    def checkHp(self):
        self.hp = max(0, min(self.hp, self.maxhp))

    def enemyDeadCheck(self):
        if self.hp == 0:
            return True

class Shop:

    armors = {"BronzeArmor":{"Name": "Bronze armor",
                             "Cost": 30,
                             "Effect": 10},
              "SilverArmor":{"Name": "Silver armor",
                             "Cost": 75,
                             "Effect": 20}}

character = Player()
character.armorsOwned.update(Shop.armors["BronzeArmor"])
character.equipArmor()

What I'm trying to do is print out all of the armors I have, print "equipped" beside it if it's equipped, receive the name of the armor to equip from input, check if it is already equipped and then equip it if it isn't equipped. 我要做的是打印出我拥有的所有装甲,如果装备有,则在其旁边打印“装备”,从输入中接收要装备的装甲的名称,检查它是否已经装备,然后装备它没有装备。 However, the error mentioned in the title is preventing me from doing that. 但是,标题中提到的错误使我无法这样做。 Why is that so and what is a string indice? 为什么会这样,什么是字符串索引?

Loops over dictionaries (for example, for i in self.armorsOwned ) return an iterable of the keys , not the entries. 字典上的循环(例如, for i in self.armorsOwned )返回的可迭代 ,而不是条目的可迭代项。 So i is being set to the key string, not the armor dictionary. 所以i被设置为键串,而不是装甲词典。

You want to turn all your loops over dictionaries to something like: 您希望将字典的所有循环都转换为类似以下内容:

for i in self.armorsOwned.values():

Dont have enough points to make comment hence posting as answer. 没有足够的分数来发表评论,因此发表为答案。 This error is generally thrown when you treat a list like a dictionary. 当您将列表视为字典时,通常会引发此错误。

It'd be helpful if you could include the #line that shows the error so that I could pin-point but to me this looks fishy: 如果您可以包括显示错误的#行,这样对我很有帮助,但对我来说,这看起来像是可疑的:

self.armorsOwned = {}

If it's just a dictionary of armor. 如果这只是盔甲的字典。 In that case, this is how you would extract the armor-name: 在这种情况下,这是提取装甲名称的方法:

        if self.armor == armor:
            print(str(select) + ". " + str(self.armorsOwned[armor]["Name"]) + " (Equipped)")
        else:
            print(str(select) + ". " + str(self.armorsOwned[armor]["Name"]))

You could also try printing the values of these variables to see what they contain before doing any string manipulation: 您还可以尝试打印这些变量的值,以查看它们包含的内容,然后再进行任何字符串操作:

def equipArmor(self):
        print(self.armorsOwned)
        for armor in self.armorsOwned:
            print(armor)
            select = 1

TypeError: string indices must be integers is a very common error in Python, especially during development. TypeError: string indices must be integers是Python中非常常见的错误,尤其是在开发过程中。 It indicates that your variable is a string, but you are trying to use it as a dictionary. 它表明您的变量是一个字符串,但是您试图将其用作字典。

example: 例:

x = {'Name': 'Bronze Armor'}
print(x['Name']) #    Bronze Armor

x = 'Bronze Armor'
print(x['Name']) #    raises TypeError: string indices must be integers

Look at error's stack trace, it will tell you in which line you made the mistake. 查看错误的堆栈跟踪,它将告诉您错误所在的行。

暂无
暂无

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

相关问题 我收到一个typeError:字符串索引必须是整数,而不是type - I'm getting a typeError: string indices must be integers, not type 为什么会出现TypeError:字符串索引必须为整数? - Why am I getting TypeError: string indices must be integers? 为什么我会收到这个 TypeError:字符串索引必须是整数 - why am i getting this TypeError: string indices must be integers 我对字符串和整数有些困惑,并且不断收到此错误:TypeError:列表索引必须是整数或切片,而不是str - I'm a little confused with strings and integers, and I keep getting this error: TypeError: list indices must be integers or slices, not str 我收到python错误TypeError:字符串索引必须是整数,而不是str - I am getting python error TypeError: String indices must be integers, not str 如何解决“ TypeError:字符串索引必须为整数”错误? - How do I resolve “TypeError: string indices must be integers” error? 设置 MongoDB 时出现此错误:字符串索引必须是整数 - I'm getting this error while setting up MongoDB : String indices must be integers python 错误 - TypeError:字符串索引必须是整数 - python error - TypeError: string indices must be integers 错误:TypeError:字符串索引必须为整数 - Error: TypeError: string indices must be integers Python错误:“ TypeError:字符串索引必须为整数” - Python Error:“TypeError: string indices must be integers”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM