pythonの文字列を配列、辞書、式に変換

655 ワード

pythonではevalが一般的ですが、この式は安全ではありません.今日stackoverflowでastというモジュールを見た
調べてみた
ast.literal_eval(node_or_string)
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.

安全なコード変換が可能で、使いやすい
import ast
userAnser = ast.literal_eval([1,2,3,4])