python eval 函数

矫情吗;* 2022-05-13 07:04 339阅读 0赞

eval()函数用处


在工作中我们经常会用到eval(),我总结了eval一下几种用处:

  1. 功能 :eval函数可以将一个字符串当成一个有效的表达式并返回结果
  2. 参数:有一下参数
        source:一个Python表达式或函数compile()返回的代码对象

        globals:可选。必须是dictionary

        locals:可选。任意map对象
    用例:

将str 转换成list

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

发表评论

表情:
评论列表 (有 0 条评论,339人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Python中的 eval 函数

      eval(<字符串>)函数时 Python 语言中一个十分重要的函数,它能够以 Pyhton 表达式的方式解析并执行字符串,并将返回结果输出。例如: >>> x