Python study notes 7-advanced iterator, python study notes 7-

Source: Internet
Author: User

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

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.