0

我有以下代码:

people = {'Bob' : {'phone' : '12',
            'birthday' : 'May',
            'address' : 'ABC',
            'interests' : ['a', 'b', 'c']},
        'Mary' : {'phone' : '13',
            'birthday' : 'April',
            'address' : 'CBA',
            'interests' : ['d', 'e', 'f']},

            response = ['']
wrong = "I don't know. Try again or type 'quit' to get out: " 
while response[0] != 'quit': 
    response = raw_input("Please enter who you're looking for, or type 'quit' to get out: ").split() 
    try:
        print "%s's %s is %s" % (response[0], response[1], people[response[0]][response[1]])  
    except KeyError: 
        print wrong,

我想让它在任何情况下都可以输入并且仍然生成正确的输出。例如

'Mary phone', 'mary Phone', 'MARY PHONE'

都给

Mary's phone number is 13.
4

2 回答 2

3

你应该使用capitalize()lower()

while response[0] != 'quit': 
    response = raw_input("Please enter who you're looking for, or type 'exit' to quit the program: ").split() 
    try:
        print "%s's %s is %s" % (response[0].capitalize(), response[1].lower(), people[response[0].capitalize()][response[1].lower()])  
    except KeyError: 
        print wrong,

如果您走这条路线,您应该将'bob'密钥更改为'Bob'...

或者,如果您重复使用结果,您可以节省更多的 CPU 周期,如下面的 rubik 所述。

while response[0] != 'quit': 
    response = raw_input("Please enter who you're looking for, or type 'exit' to quit the program: ").split() 
    try:
        fn, thing = response[0].capitalize(), response[1].lower()
        print "%s's %s is %s" % (fn, thing, people[fn][thing])  
    except KeyError: 
        print wrong,
于 2012-05-08T14:45:47.890 回答
2

尝试使用 . 将输入转换为小写,以确保输入始终为小写str.lower()。然后确保您的所有people{}名称也是小写以便于搜索,并在执行输出时将输出格式化回大写名称。

于 2012-05-08T14:46:25.880 回答