【Python】數據類型的轉換 eval和ast.literal_eval


eval 用來執行一個字符串表達式,並返回表達式的值

  • eval() 把數據還原成它本身或者是能夠轉化成的數據類型,(即:可以實現從tuple 元組,list列表,dict字典型的 str字符串到元組,列表,字典的轉換
    • string <==> dict
      str_dict= '{"name":"zhangsan"}'
      chg_dict = eval(str_dict)
      
      print(str_dict, chg_dict)
      print(type(str_dict), type(chg_dict))
      {"name":"zhangsan"} {'name': 'zhangsan'}
      <class 'str'> <class 'dict'>
      
      進程已結束,退出代碼0
      執行結果

       

    • string <==> tuple
      str_tuple = '(4,5,6)'
      chg_tuple = eval(str_tuple)
      
      print(str_tuple, chg_tuple)
      print(type(str_tuple), type(chg_tuple))
      (4,5,6) (4, 5, 6)
      <class 'str'> <class 'tuple'>
      
      進程已結束,退出代碼0
      執行結果

       

    • string  <==> list
      str_list = '[1,2,2]'
      chg_list = eval(str_list)
      
      print(str_list,chg_list)
      print(type(str_list),type(chg_list))
      [1,2,2] [1, 2, 2]
      <class 'str'> <class 'list'>
      
      進程已結束,退出代碼0
      執行結果

       

  •  eval()  還可以對字符串型的輸入直接計算
    • input
      a = input("Plase input a value string:")
      b = input("Plase input a value string:")
      normal_value = a + b
      eval_value = eval(a) + eval(b)
      print("正常value輸出:",normal_value)
      print("使用eval輸出:",eval_value)
      Plase input a value string:1
      Plase input a value string:8
      正常value輸出: 18
      使用eval輸出: 9
      
      進程已結束,退出代碼0
      執行結果

       

    •  對所有能解析的字符串都做處理(比如讀取文件,路徑,目錄, 刪除文件等)
      read_path = "__import__('os').getcwd()"
      # read_dir = "__import__('os').system('dir')"
      print("正常輸出:",read_path)
      print("轉換輸出:",eval(read_path))
      # print(eval(read_dir))
      正常輸出: __import__('os').getcwd()
      轉換輸出: Z:\Python\xxx\common
      
      進程已結束,退出代碼0
      執行結果

       

    • 通過變量內容作為函數名調用 eval函數

      # 賦值函數名稱
      a = "b"
      # 定義函數
      def b():
          print(123)
      # 通過變量調用函數
      eval(a)()

       

      # 賦值函數名稱
      a = "b()"
      # 定義函數
      def b():
          print(123)
      # 通過變量調用函數
      eval(a)

 

ast.literal_eval()

  • ast模塊就是幫助Python應用來處理抽象的語法解析的

  • literal_eval() 會判斷需要計算的內容計算后是不是合法的python類型,相較於eval()較安全 
    • 示例1:
      import ast
      
      read_path = "__import__('os').getcwd()"
      # read_dir = "__import__('os').system('dir')"
      print("正常輸出:",read_path)
      print("eval轉換輸出:",eval(read_path))
      try:
          print("asr轉換輸出:",ast.literal_eval(read_path))
      except Exception as e:
          print("Exception 原因:",e)
      
      normal_value = "(1,2,3)"
      print("asr轉換輸出:",ast.literal_eval(normal_value))
      正常輸出: __import__('os').getcwd()
      eval轉換輸出: Z:\Python\xxxx\common
      Exception 原因: malformed node or string: <_ast.Call object at 0x00C70298>
      asr轉換輸出: (1, 2, 3)
      
      進程已結束,退出代碼0
      執行結果
    •  示例2:
      ast_tuple = "(1,2,3)"
      print("ast轉換輸出:",ast.literal_eval(ast_tuple))
      ast_list = "[1,2,3]"
      print("ast轉換輸出:",ast.literal_eval(ast_list))
      ast_dict = "{'name':'zhangsan'}"
      print("ast轉換輸出:",ast.literal_eval(ast_dict))
      
      # 將dict 字段的'替換為"
      rep = ast_dict.replace("'",'"')
      
      print("reolace 替換",rep)
      print("ast轉換輸出:",ast.literal_eval(rep))
      ast轉換輸出: (1, 2, 3)
      ast轉換輸出: [1, 2, 3]
      ast轉換輸出: {'name': 'zhangsan'}
      reolace 替換 {"name":"zhangsan"}
      ast轉換輸出: {'name': 'zhangsan'}
      
      進程已結束,退出代碼0
      執行結果

       

    


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM