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