Python:eval()将值强制转换为浮点数?
16lz
2021-01-22
Is there a way to execute an eval
-like function that coerces its values to floating point? I am hoping to
有没有办法执行类似eval的函数,将其值强制转换为浮点值?我希望
eval('1/3')
and have it return the floating point value .333333 rather than the integer value 0.
并让它返回浮点值.333333而不是整数值0。
5 个解决方案
#1
15
Grab the compiler flag for __future__.division
, pass it and your code to compile()
, then run eval()
on the returned code object.
抓取__future __。division的编译器标志,将它和你的代码传递给compile(),然后在返回的代码对象上运行eval()。
(note by mh) This has the added advantage of not changing the division operation globally, which might have unexpected side effects. (end note)
(注意mh)这具有不改变全局分割操作的附加优点,这可能具有意想不到的副作用。 (尾注)
>>> import __future__
>>> eval(compile('1/3', '<string>', 'eval', __future__.division.compiler_flag))
0.33333333333333331
更多相关文章
- 怎样写贪吃蛇小游戏?用100行python代码轻松解决!
- 建模分析之机器学习算法(附python&R代码)
- 读取python中的unicode文件,该文件以与python源代码相同的方式声
- 自动完成在VS代码和Python中的自动化对象
- 在生产中是否应该减少服务器代码?
- 支持c和python之间的跨语言(c)标记的代码编辑器
- 【小白自学笔记】【机器学习实战】【Python代码逐行理解】CH02
- 三个猜数字游戏代码(Python)
- 在混合的Bash-Python代码片段中,变量的双引号和单引号