zoukankan      html  css  js  c++  java
  • python eval内置函数作用

    功能:将字符串str当成有效的表达式来求值并返回计算结果。

      语法: eval(source[, globals[, locals]]) -> value

      参数:

        source:一个Python表达式或函数compile()返回的代码对象

        globals:可选。 变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。

        locals:可选。 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。

    # 将字符串中的元组获取出来
    s1 = '(1,2,3)'
    res = eval(s1)
    print(res, type(res))
    # 结果:(1, 2, 3) <class 'tuple'>
    

      

    # 将字符串中的列表获取出来
    s2 = '[11,22,33]'
    res1 = eval(s2)
    print(res1, type(res1))
    # 结果:[11, 22, 33] <class 'list'>
    

      

    # 将字符串中的字典获取出来
    s3 = "{'name':'zhangs','age':20}"
    res2 = eval(s3)
    print(res2, type(res2))
    # # 结果:{'name': 'zhangs', 'age': 20} <class 'dict'>
    

      

    # 将字符串中的数字获取出来
    s5 = '666'
    res5 = eval(s5)
    print(res5, type(res5))
    # 结果:666 <class 'int'>
    

      

    # 注意:如果是一个纯粹的字符串,那么使用eval进行转换之后就变成了一个变量名
    s4 = 'python'
    res3 = eval(s4)
    print(res3)
    # 结果:NameError: name 'python' is not defined
    

      

  • 相关阅读:
    【LeetCode】Rotate Image
    【LeetCode】Combinations
    【LeetCode】Minimum Depth of Binary Tree
    【LeetCode】Reverse Nodes in k-Group
    【LeetCode】Reverse Linked List II
    【LeetCode】Insert Interval
    【LeetCode】Insertion Sort List
    python之列表生成式
    python 模块和模块sys.argv
    python 异常处理
  • 原文地址:https://www.cnblogs.com/pengjt/p/11711539.html
Copyright © 2011-2022 走看看