PYthon第十三天

來源:互聯網
上載者:User

標籤:str   變數   內建函數   nbsp   func   列印   個數   字元   ict   

內建函數 eval

eval 執行字串表示的代碼,並把結果返回

1 i1 = eval(‘12+22‘)     兩個數值相加2 print(i1, type(i1))    34 <class ‘int‘>3 n = 24 i2 = eval(‘n+3‘)       變數的值和數值相加5 print(i2, type(i2))    5 <class ‘int‘>6 eval(‘print(123)‘)     123     列印語句7 s1 = eval("‘a‘+‘b‘")   兩個字串相加8 print(s1, type(s1))     ab <class ‘str‘>

 下面是使用報錯的例子

1 s1 = eval(‘abc‘)2 print(s1)

看下報錯的原因:

eval, 把 ‘abc‘ 解讀成 一個變數,

而程式中卻沒有這個變數, 所以報錯.

因此,可以發現, 為什麼 eval 可以執行 字串‘n + 2‘ 的代碼

正確例子如下:

1 abc = {‘a‘: 1}2 s1 = eval(‘abc‘)3 print(s1, type(s1))    {‘a‘: 1} <class ‘dict‘>

可以把 abc 這個變數, 換成可以賦值的任何元素, 甚或是函數名

1 def foo():2     print(‘123‘)3 4 5 abc = foo6 s1 = eval(‘abc‘)7 print(s1, type(s1))8 9 s1()

執行結果如下:

1 <function foo at 0x10dd16ea0> <class ‘function‘>2 123

 

PYthon第十三天

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.