【问题标题】:Python - File handling - Can't convert 'int' object to str implicitly [duplicate]Python - 文件处理 - 无法将'int'对象隐式转换为str [重复]
【发布时间】:2023-04-06 11:31:01
【问题描述】:

我正在尝试将冒险游戏的故事从文件读入字典,然后让玩家通过“下一步”或“返回”来指示游戏的进展。
第一个功能工作正常。
打印“print(room_dict[0])”将调用第一个房间描述。

def room(room_dict):
    with open("worlds\\rooms.txt", "r") as room_file:
        for line in room_file:
            room_key = int(line.strip())
            room_description = next(room_file).strip()
            room_dict[room_key] = room_description
        return room_dict

room_dict = {}
room = room(room_dict)

def room_interaction():
    print(room_dict[0])
    VALID = ("next", "back", "search")
    current = (room_dict[0])

    room_choice = input("What do you want to do?: ").lower()
    while room_choice not in VALID:
        room_choice = input("What do you want to do?: ").lower()
    if room_choice == "next":
        print(room_dict[current + 1])
        current = (room_dict[current + 1])
    elif room_choice == "back":
        print(room_dict[current - 1])
        current = (room_dict[current - 1])

当我尝试加一或减一时出现问题,我得到了回溯:

File "C:\room interaction test.py", line 23, in room_interaction
    print(room_dict[current + 1])
TypeError: Can't convert 'int' object to str implicitly

我知道 +1/-1 方法可能不是最好的,但它是我能在短时间内想到的最简单的方法。关于如何以这种方式在字典中移动的任何其他想法?

【问题讨论】:

  • 如果你不能隐式转换你总是可以显式转换...print(str(room_dict[current + 1]))
  • 所以这个问题在我回答之前就结束了,但你的错误就在这里:current = (room_dict[0])。这意味着 current 是房间描述,不是房间钥匙。你真正想做的是current = 0

标签:
python
string
dictionary
int
file-handling