Python study notes 7-advanced iterator, python study notes 7-
Evaluate any string as a python expression:
Eval () method:
Eval (source [, globals [, locals])-> value
Evaluate the source in the context of globals and locals.
The source may be a string representing a Python expression
Or a code object as returned by compile ().
The globals must be a dictionary and locals can be any mapping,
Defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
Usage:
>>> eval('1+1==2')True>>> eval('1+1==3')False>>> eval('9567+1085 == 10652')True>>> eval('"A"+"B"')'AB'>>> eval('"MARK".translate({65:79})')'MORK'>>> eval('"AAAAA".count("A")')
>>> eval("x*5",{}, {})Traceback (most recent call last): File "<pyshell#120>", line 1, in <module> eval("x*5",{}, {}) File "<string>", line 1, in <module>NameError: name 'x' is not defined>>> eval("x*5",{"x":x},{})25>>> import math>>> eval("math.sqrt(x)",{"x":x},{})Traceback (most recent call last): File "<pyshell#123>", line 1, in <module> eval("math.sqrt(x)",{"x":x},{}) File "<string>", line 1, in <module>NameError: name 'math' is not defined
Note:
The second and third parameters passed to the eval () functions assume the role of a global and local namespace evaluate expression.
Eval () is insecure. To safely evaluate untrusted expressions, You need to define a global namespace dictionary that maps "_ builtins _" to none. Internally, the "Built-in" function is included in a pseudo module named "_ builtins.
Re. findall () -- returns all letters in the string
Set () -- returns all different letters in the string