我正在尝试在PyCharm中创建一个基于文本的冒险游戏,而我现在要编码的是当玩家打开一组抽屉向里看时。我想让他们知道他们打开的抽屉里有多少物品,以及这些物品是什么。但我不断收到一条消息,说Expected type 'str', got 'List[str]' instead
。
该如何解决?问题就在代码底部。
if "go to drawers" in choice:
drawerStates = '1 and 2 are open. 3 is missing a handle.'
drawer1Inventory = ['lipstick', 'cute photo of a dog', 'socks']
drawer2Inventory = ['T-shirt', 'jeans', 'pants', 'socks']
drawer3Inventory = ['key']
subLocation = 'drawers'
slowprint('You go to the set of drawers.')
time.sleep(1)
slowprint('''They're very old and worn down. Only 2 out of the 3 have handles.
You need to find the third handle to open it.''')
while subLocation == 'drawers':
slowprint('What would you like to do? (Type help for help)')
choice = input('>')
if 'location' in choice:
slowprint('You are at the ' + subLocation + ' in the ' + location)
if 'help' in choice:
slowprint('Right now drawers ' + drawerStates)
slowprint('''Type 'open drawer 1' to open the 1st drawer.
Type 'open drawer 2' to open the 2nd.
Type 'open drawer 3' to open the 3rd''')
if 'open drawer 1' in choice:
slowprint('Currently, there are ' + len(drawer1Inventory) + 'items in this drawer.')
slowprint('Items in drawer 1:' + drawer1Inventory)
答案 0 :(得分:2)
在python中,您不能添加字符串和整数。
您应该替换
slowprint('Currently, there are ' + len(drawer1Inventory) + 'items in this drawer.')
作者:
slowprint(f'Currently, there are {len(drawer1Inventory)} items in this drawer.')
此外,您不能添加字符串和列表,应替换:
slowprint('Items in drawer 1:' + drawer1Inventory)
作者:
slowprint(f'Items in drawer 1: {drawer1Inventory}')
(前提是您使用的是Python 3.6 +)
答案 1 :(得分:2)
drawer1Inventory是一个列表。如果您希望它打印项目,请尝试使用join,它将使用所有列表项,并输出一个字符串,其中每个列表项都用逗号分隔:
slowprint('Items in drawer 1:' + ','.join(drawer1Inventory))