Skip to main content
 首页 » 编程设计

python之在 python 中使用 compile 和 eval 时出现奇怪的问题

2025年05月04日12lidabo

我正在尝试使用 python eval 和 compile 来解析和评估公式。对于一种情况,它正在工作,对于其他情况,它不是。见下文: 这工作正常

>>> formula = '(00*3600)+(03*60)+10' 
>>> eval(compile(formula, '<string>', 'eval')) 
190 

但这会出错

>>> formula = '(00*3600)+(08*60)+53' 
>>> eval(compile(formula, '<string>', 'eval')) 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
  File "<string>", line 1 
    (00*3600)+(08*60)+53 
                ^ 
SyntaxError: invalid token 

请帮忙。我无法理解。我正在使用 Python 2.7.5

请您参考如下方法:

前导零使 python 将该值视为八进制数。 08 无效,因为八进制数只能包含数字 0-7。您应该删除前导零。