我们如何使用ast.literal_eval实现类似eval的功能

时间:2020-05-20 16:09:56

标签: python

使用eval,我可以得到以下信息:

str1 = "23145"
str2 = "str1"
print(str2)

输出:

23145

做得很好。

ast.literal_eval不能正常工作:

import ast
print(ast.literal_eval(str2))

获取:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Volumes/app/python/anaconda3/lib/python3.7/ast.py", line 91, in literal_eval
    return _convert(node_or_string)
  File "/Volumes/app/python/anaconda3/lib/python3.7/ast.py", line 90, in _convert
    return _convert_signed_num(node)
  File "/Volumes/app/python/anaconda3/lib/python3.7/ast.py", line 63, in _convert_signed_num
    return _convert_num(node)
  File "/Volumes/app/python/anaconda3/lib/python3.7/ast.py", line 55, in _convert_num
    raise ValueError('malformed node or string: ' + repr(node))
ValueError: malformed node or string: <_ast.Name object at 0x10ce34190>

1 个答案:

答案 0 :(得分:0)

使用globals()获得解决方案。

str1 = “shiva”
str2 = “str1"
print(globals()[str2])

O / P:湿婆