將任何字符串作為python表達(dá)式求值:
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()函數(shù)傳遞的第二、第三個(gè)參數(shù)擔(dān)當(dāng)了求值表達(dá)式是全局和局部名字空間的角色
eval()是不安全的,為了安全的求值不受信任的表達(dá)式,需要定義一個(gè)將"__builtins__"映射為none的全局名字空間字典。在內(nèi)部,“內(nèi)建”函數(shù)包含在一個(gè)叫“__builtins__"的偽模塊內(nèi)。
re.findall() -- 返回字符串中所有字母
set() -- 返回字符串中所有不同的字母
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注