python庫——ast.literal_eval

參考文獻:

  • https://docs.python.org/zh-cn/3/library/ast.html
  • https://kite.com/python/docs/ast
  • https://kite.com/python/docs/ast.literal_eval

literal_eval

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.

安全地評估表達式節點或包含Python表達式的Unicode或Latin-1編碼的字符串。提供的字符串或節點只能由以下Python文字結構組成:字符串,數字,元組,列表,字典,布爾值和無。
這可用於安全地評估包含來自不受信任來源的Python表達式的字符串,而無需自己解析值。

import ast
dictionary = ast.literal_eval("{'a': 1, 'b': 2}")
print type(dictionary)
# OUTPUT: <type 'dict'>
print dictionary
# OUTPUT: {'a': 1, 'b': 2}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章