zoukankan      html  css  js  c++  java
  • Python学习札记-eval函数

    eval()函数

            eval()官方文档里面给出来的功能解释是:将字符串string对象转化为有效的表达式参与求值运算返回计算结果

           语法上:调用的是:eval(expression,globals=None, locals=None)返回的是计算结果

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

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

      参数:

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

        globals:可选。必须是dictionary

        locals:可选。任意map对象

      实例展示:

    1 可以把list,tuple,dict和string相互转化。
     2 #################################################
     3 字符串转换成列表
     4 >>>a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
     5 >>>type(a)
     6 <type 'str'>
     7 >>> b = eval(a)
     8 >>> print b
     9 [[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
    10 >>> type(b)
    11 <type 'list'>
    12 #################################################
    13 字符串转换成字典
    14 >>> a = "{1: 'a', 2: 'b'}"
    15 >>> type(a)
    16 <type 'str'>
    17 >>> b = eval(a)
    18 >>> print b
    19 {1: 'a', 2: 'b'}
    20 >>> type(b)
    21 <type 'dict'>
    22 #################################################
    23 字符串转换成元组
    24 >>> a = "([1,2], [3,4], [5,6], [7,8], (9,0))"
    25 >>> type(a)
    26 <type 'str'>
    27 >>> b = eval(a)
    28 >>> print b
    29 ([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))
    30 >>> type(b)
    31 <type 'tuple'>

    参考:

        http://www.cnblogs.com/dadadechengzi/p/6149930.html

  • 相关阅读:
    立体匹配算法(转载)
    校招总结
    tcpip概述
    Matlab2014a 提示未找到支持的编译器或 SDK的解决方法
    CSS3 实现简单轮播图
    css3实现switch开关效果
    Sass的使用和基础语法
    Git的安装和使用记录
    jQuery淡入淡出效果轮播图
    JavaScript焦点轮播图
  • 原文地址:https://www.cnblogs.com/sunshine88/p/8313457.html
Copyright © 2011-2022 走看看