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: 
print dictionary
# OUTPUT: {'a': 1, 'b': 2}

你可能感兴趣的:(Python,ast,literal_eval,python,eval)