Python - File handling - Can't convert 'int' object to str implicitly
本问题已经有最佳答案,请猛点这里访问。
我试图把冒险游戏的故事从一个文件读到一本字典里,然后让玩家用"下一步"或"上一步"命令游戏的进展。第一个功能正常。打印"print(room_dict[0])"将调用第一个房间描述。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | def room(room_dict): with open("worlds\ ooms.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]) |
当我尝试加一或减一时,问题就出现了,我得到了回溯:
1 2 3 4 | File"C: oom interaction test.py", line 23, in room_interaction print(room_dict[current + 1]) TypeError: Can't convert 'int' object to str implicitly |
号
我知道+1/-1方法可能不是最好的,但这是我可以在短时间内想到的最简单的方法。关于如何以这种方式在字典中移动还有其他想法吗?
1 | "123" + 1 |
返回?字符串
1 | print(room_dict[int(current) + 1]) |
号
但我真的不知道-我猜
另一种可能是您的逻辑刚刚被混淆,并且您确实打算让一个整型变量跟踪当前房间ID,但是将其与当前房间描述混淆。