The use of the Python eval () function

Source: Internet
Author: User
Tags string back

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

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.