gpt4 book ai didi

python - 为什么 ast.literal_eval ('5 * 7' ) 失败了?

转载 作者:太空狗 更新时间:2023-10-29 20:39:23 26 4
gpt4 key购买 nike

为什么 5 * 7 的文字计算失败,而 5 + 7 却没有?

import ast

print(ast.literal_eval('5 + 7'))
# -> 12

print(ast.literal_eval('5 * 7'))
# ->
Traceback (most recent call last):
...
ValueError: malformed node or string: <_ast.BinOp object at ...>

documentation不解释这个。

我在 SO 上回答了这个问题后发现了这个问题:Getting the result of a string .

最佳答案

ast.literal_eval() 接受评估数据中的 + 因为 5+2j (复数* ) 是有效的文字。这同样适用于 -。为了保持代码简单,没有尝试排除 +- 作为二元运算符。

不允许有其他操作符;该函数应该只接受文字,不接受表达式。

换句话说,5 + 7 起作用是一个错误,但在不破坏对构造复数的支持的情况下很难修复。 implementation将使用限制为数字操作数、一元 +- 或其他二元运算符(因此您不能使用它们来连接列表或产生集合差异)。

另请参阅几个相关的 Python bugtracker 条目:#25335 ast.literal_eval fails to parse numbers with leading "+" , #22525 ast.literal_eval() doesn't do what the documentation says#4907 ast.literal_eval does not properly handled complex numbers


* 从技术上讲,2j 是一个有效的文字; Python 将 5+2j 解析为 int(5) binop(+) complex(0, 2),然后才生成一个 complex(5, 2) 实际执行加法时从结果中提取对象。

关于python - 为什么 ast.literal_eval ('5 * 7' ) 失败了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40584417/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com