有没有办法执行类似eval
的函数,将其值强制转换为浮点数?我希望
eval('1/3')
并返回浮点值.333333而不是整数值0。
答案 0 :(得分:15)
获取__future__.division
的编译器标志,将其传递给compile()
,然后在返回的代码对象上运行eval()
。
(请注意......)这样做的另一个好处是不会全局更改分割操作,这可能会产生意想不到的副作用。 (尾注)
>>> import __future__
>>> eval(compile('1/3', '<string>', 'eval', __future__.division.compiler_flag))
0.33333333333333331
答案 1 :(得分:6)
你的问题是:我怎样才能让Python默认进行浮点除法。答案是:
from __future__ import division
答案 2 :(得分:3)
问题是表达式中没有浮点值。
试试这个eval('1/3.0')
答案 3 :(得分:2)
默认情况下,这适用于Python3
Python 3.2 (r32:88445, Dec 8 2011, 15:26:51)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> eval("1/3")
0.3333333333333333
对于Python2,您可以在命令行上传递-Qnew
(相当于from __future__ import division
$ python -Qnew
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> eval("1/3")
0.3333333333333333
答案 4 :(得分:1)
根据Lafada的回答,如果您从变量中获取输入字符串:
>>> string = '1/3'
>>> print eval(string+'.0')
0.333333333333