【发布时间】:2019-08-24 08:07:12
【问题描述】:
当我尝试输入时"help move" 此代码将相应的帮助消息打印到 "move" 和默认值。但是,如果我理解 dict.get(key[, value]) 正确,则只有在键(例如“运行”而不是“移动”)不在字典中时才会出现默认值。
我尝试检查我的密钥是否为字符串且没有空格。不知道其他什么/如何检查。
#!/usr/bin/env python3
def show_help(*args):
if not args:
print('This is a simple help text.')
else:
a = args[0][0]
str_move = 'This is special help text.'
help_cmd = {"movement" : str_move, "move" : str_move,
"go" : str_move}
#print(a) # print out the exact string
#print(type(a)) # to make sure "a" is a string (<class 'str'>)
print(help_cmd.get(a), 'Sorry, I cannot help you.')
commands = {"help" : show_help, "h" : show_help}
cmd = input("> ").lower().split(" ") # here comes a small parser for user input
try:
if len(cmd) > 1:
commands[cmd[0]](cmd[1:])
else:
commands[cmd[0]]()
except KeyError:
print("Command unkown.")
如果我输入help move,我预计输出This is a special help text.,但实际输出是This is special help text. Sorry, I cannot help you with "move".。
【问题讨论】:
标签: python-3.x string dictionary output default