What does Python's eval() do?

前端 未结 10 2094
后悔当初
后悔当初 2020-11-22 01:48

In the book that I am reading on Python, it keeps using the code eval(input(\'blah\'))

I read the documentation, and I understand it, but I still do no

10条回答
  •  忘了有多久
    2020-11-22 02:41

    One of useful applications of eval() is to evaluate python expressions from string. For example load from file string representation of dictionary:

    running_params = {"Greeting":"Hello "}
    fout = open("params.dat",'w')
    fout.write(repr(running_params))
    fout.close()
    

    Read it out as a variable and edit it:

    fin = open("params.dat",'r')
    diction=eval(fin.read())
    diction["Greeting"]+="world"
    fin.close()
    print diction
    

    Output:

    {'Greeting': 'Hello world'}
    

提交回复
热议问题