Python學習筆記7-進階迭代器

來源:互聯網
上載者:User

標籤:

將任何字串作為python運算式求值:

eval()方法:

eval(source[, globals[, locals]]) -> value
Evaluate the source in the context of globals and locals.
The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.

用法:

>>> eval(‘1+1==2‘)True>>> eval(‘1+1==3‘)False>>> eval(‘9567+1085 == 10652‘)True>>> eval(‘"A"+"B"‘)‘AB‘>>> eval(‘"MARK".translate({65:79})‘)‘MORK‘>>> eval(‘"AAAAA".count("A")‘)

 

>>> eval("x*5",{}, {})Traceback (most recent call last):  File "<pyshell#120>", line 1, in <module>    eval("x*5",{}, {})  File "<string>", line 1, in <module>NameError: name ‘x‘ is not defined>>> eval("x*5",{"x":x},{})25>>> import math>>> eval("math.sqrt(x)",{"x":x},{})Traceback (most recent call last):  File "<pyshell#123>", line 1, in <module>    eval("math.sqrt(x)",{"x":x},{})  File "<string>", line 1, in <module>NameError: name ‘math‘ is not defined

 註:

給eval()函數傳遞的第二、第三個參數擔當了求值運算式是全域和局部名字空間的角色

eval()是不安全的,為了安全的求值不受信任的運算式,需要定義一個將"__builtins__"映射為none的全域名字空間字典。在內部,“內建”函數包含在一個叫“__builtins__"的偽模組內。

 

re.findall() -- 返回字串中所有字母

set() --  返回字串中所有不同的字母

 

Python學習筆記7-進階迭代器

相關文章

聯繫我們

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