Python中的eval函数


一、简介:

  eval函数就是实现list、dict、tuple与str之间的转化,而str函数实现把list 、dict、tuple转换成字符串

      1、字符串转化为列表

  

1 # 字符串转化为列表
2 a = "[[1,2],[3,4],[5,6],[7,8],[9,10]]"
3 print(type(a))
4 b=eval(a)
5 print(type(b))
6 print(b)
1 <class 'str'>
2 <class 'list'>
3 [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]

 

  2、字符串转化为字典

1 # 字符串转换成字典
2 a="{1:'a',2:'b'}"
3 print(type(a))
4 b=eval(a)
5 print(type(b))
6 print(b)
1 <class 'str'>
2 <class 'dict'>
3 {1: 'a', 2: 'b'}

 

  3、字符串转化为元组

1 # 字符串转换成元组
2 a='([1,2],[3,4],[5,6],[7,8],[9,10])'
3 print(type(a))
4 b=eval(a)
5 print(type(b))
6 print(b)
1 <class 'str'>
2 <class 'tuple'>
3 ([1, 2], [3, 4], [5, 6], [7, 8], [9, 10])

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM