试图通过用户输入调用函数

时间:2013-03-24 02:53:57

标签: python string function

def monster(name):

    with open('yvd.txt') as fd:
        input=[x.strip('|').split('|') for x in fd.readlines()]
        to_search={x[0]:x for x in input}
        print('\n'.join(to_search[name]))
monster_name=input('Input monster to search: ')
monster(monster_name)

好的,所以我试图通过用户输入调用函数monsterinput要求用户输入要搜索的怪物的名称。然后函数monster搜索输入的怪物并将其打印出来。但是如何让它在函数中可以调用字符串?

输出示例:

Input monster to search: Boogie Man
    Traceback (most recent call last):
    File "C:\Users\Trevor\Desktop\yvd_read.py", line 8, in <module>
    monster(monster_name)
    TypeError: 'str' object is not callable
>>> 

2 个答案:

答案 0 :(得分:0)

问题是方法input。您应该使用raw_input代替。输入尝试评估字符串,但raw_input只是将用户写入的字符串放在变量中。

答案 1 :(得分:0)

您需要替换python内置函数raw_input来读取值而不是输入。请参阅input function here的文档。这是更新的代码:

def monster(name):

with open('yvd.txt') as fd:
    user_input=[x.strip('|').split('|') for x in fd.readlines()]
    to_search={x[0]:x for x in input}
    print('\n'.join(to_search[name]))

monster_name=raw_input('Input monster to search: ')
monster(monster_name)