当我尝试输入例如“帮助移动”此代码将相应的帮助消息打印为“移动”和默认值。但是,如果我对dict.get(key [,value])的理解正确,那么仅当键(例如“ run”而不是“ move”)不在词典中时,默认值才会出现。
我试图检查我的钥匙是否是字符串并且没有空格。不知道什么/如何检查。
#!/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.")
如果我输入This is a special help text.
,我期望输出help move
,但实际输出是This is special help text. Sorry, I cannot help you with "move".
。
答案 0 :(得分:1)
问题的症结所在:
print(help_cmd.get(a), 'Sorry, I cannot help you with "{}".'.format(a))
您的默认值不在get的调用范围内,因此它不充当默认值,而是被串联起来。要使其成为默认设置,请修改为:
print(help_cmd.get(a, 'Sorry, I cannot help you with "{}".'.format(a)))