Python學習劄記-eval函數

來源:互聯網
上載者:User

標籤:value   eval   post   glob   local   執行個體   官方文檔   point   string   

eval()函數

        eval()官方文檔裡面給出來的功能解釋是:將字串string對象轉化為有效運算式參與求值運算返回計算結果

       文法上:調用的是:eval(expression,globals=None, locals=None)返回的是計算結果

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

  文法: eval(source[, globals[, locals]]) -> value

  參數:

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

    globals:可選。必須是dictionary

    locals:可選。任意map對象

  執行個體展示:

1 可以把list,tuple,dict和string相互轉化。 2 ################################################# 3 字串轉換成列表 4 >>>a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]" 5 >>>type(a) 6 <type ‘str‘> 7 >>> b = eval(a) 8 >>> print b 9 [[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]10 >>> type(b)11 <type ‘list‘>12 #################################################13 字串轉換成字典14 >>> a = "{1: ‘a‘, 2: ‘b‘}"15 >>> type(a)16 <type ‘str‘>17 >>> b = eval(a)18 >>> print b19 {1: ‘a‘, 2: ‘b‘}20 >>> type(b)21 <type ‘dict‘>22 #################################################23 字串轉換成元組24 >>> a = "([1,2], [3,4], [5,6], [7,8], (9,0))"25 >>> type(a)26 <type ‘str‘>27 >>> b = eval(a)28 >>> print b29 ([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))30 >>> type(b)31 <type ‘tuple‘>

參考:

    http://www.cnblogs.com/dadadechengzi/p/6149930.html

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.