Python eval 函數妙用

來源:互聯網
上載者:User

標籤:運算式   repr   log   print   eval   bsp   一個   style   div   

eval

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

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

參數:

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

globals:可選。必須是dictionary

locals:可選。任意map對象

執行個體展示:

可以把list,tuple,dict和string相互轉化。#################################################字串轉換成列表>>>a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]">>>type(a)<type ‘str‘>>>> b = eval(a)>>> print b[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]>>> type(b)<type ‘list‘>#################################################字串轉換成字典>>> a = "{1: ‘a‘, 2: ‘b‘}">>> type(a)<type ‘str‘>>>> b = eval(a)>>> print b{1: ‘a‘, 2: ‘b‘}>>> type(b)<type ‘dict‘>#################################################字串轉換成元組>>> a = "([1,2], [3,4], [5,6], [7,8], (9,0))">>> type(a)<type ‘str‘>>>> b = eval(a)>>> print b([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))>>> type(b)<type ‘tuple‘>

 

eval函數將字串當成有效Python運算式來求值,並返回計算結果

x = 1eval(‘x+1‘)eval(‘x==1‘)

 

與之對應的repr函數,它能夠將Python的變數和運算式轉換為字串表示

repr(x==1)repr(x+1)

 

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.