The use of the Python eval () function
The eval (str) function is powerful, as the official explanation is that the string STR is evaluated as a valid expression and returns the result of the calculation. So it's good to combine math as a calculator.
The most common functions of the eval () function are:
1. Evaluates a valid expression in a string and returns the result
1 >>> eval ('pow (2,2)')2 43 >>> Eval ('2 + 2')4 45 >>> eval ("n + 4")6 85
2. Convert the string to the corresponding object (such as the conversion between list, tuple, dict, and string)
1>>> A ="[ [up], [3,4], [5,6], [7,8], [9,0]]"2>>> B =Eval (a)3>>>b4[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]5>>> A ="{1: ' xx ', 2: ' yy '}"6>>> C =Eval (a)7>>>C8{1:'xx', 2:'yy'}9>>> A ="(1,2,3,4)"Ten>>> d =Eval (a) One>>>D A(1, 2, 3, 4)
3. Convert the string back to the object using the anti-quote conversion
1>>> List1 = [1,2,3,4,5]2>>>' List1 '3 '[1, 2, 3, 4, 5]'4>>>type (' List1 ')5<type'Str'>6>>>Type (eval (' List1 '))7<type'List'>8>>> A =eval (' List1 ')9>>>aTen[1, 2, 3, 4, 5]
The use of the Python eval () function