• Python学习笔记7-高级迭代器


    将任何字符串作为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() --  返回字符串中所有不同的字母

  • 相关阅读:
    shell脚本:/bin/sh^M: bad interpreter: No such file or directory。(转)
    Buffer在JDK中的基本说明

    清除版本控制信息针对 SVN
    修改——对密码进行加密
    省市加载javascript
    visual studio 2010 中 javascript 提示文本
    折腾自己的博客样式,自适应两列布局
    给动态加载的图片添加延迟加载(附在线demo)
    44种IE css bug实例测试总结(转载)
  • 原文地址:https://www.cnblogs.com/summerlong/p/4516689.html
Copyright © 2020-2023  润新知