Python eval()函數

來源:互聯網
上載者:User

標籤:pytho   val   應用   int   glob   ict   local   pre   eva   

本文內容

      1、eval()函數介紹
      2、eval()應用

一、eval()函數介紹

eval(source[, globals[, locals]])

  功能:將字串str當成有效運算式來求值並返回計算結果

  參數:

    source:一個Python運算式或函數compile()返回的代碼對象

    globals:可選。必須是dictionary

    locals:可選。任意map對象
    

二、eval()應用

不傳入傳入globals 、locals

data1 = ‘1‘ret1 = eval(data1)print(ret1, type(ret1))  # 1 <class ‘int‘>data2 = ‘[1,2,3,4]‘ret2 = eval(data2)print(ret2, type(ret2))  # [1, 2, 3, 4] <class ‘list‘>data3 = ‘(1,2 ,3,4)‘ret3 = eval(data3)print(ret3, type(ret3))  # (1, 2, 3, 4) <class ‘tuple‘>data4 = ‘{"name":"allen", "age":15}‘ret4 = eval(data4)print(ret4, type(ret4))  # {‘name‘: ‘allen‘, ‘age‘: 15} <class ‘dict‘>data5 = ‘{1,2,3,4}‘ret5 = eval(data5)print(ret5, type(ret5))  # {1, 2, 3, 4} <class ‘set‘>ret6 = eval(‘1+1‘)print(ret6, type(ret6))  # 2 <class ‘int‘>

傳入globals 、locals

x = 2y = 2num2 = eval("x+y")print(num2)  # 4num3 = eval("x+y", globals()) print(num3)  # 2num4 = eval("x+y",globals(),locals()) print(num4)  # 4

Python eval()函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.