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

更多相关文章

  1. 怎样写贪吃蛇小游戏?用100行python代码轻松解决!
  2. 建模分析之机器学习算法(附python&R代码)
  3. 读取python中的unicode文件,该文件以与python源代码相同的方式声
  4. 自动完成在VS代码和Python中的自动化对象
  5. 在生产中是否应该减少服务器代码?
  6. 支持c和python之间的跨语言(c)标记的代码编辑器
  7. 【小白自学笔记】【机器学习实战】【Python代码逐行理解】CH02
  8. 三个猜数字游戏代码(Python)
  9. 在混合的Bash-Python代码片段中,变量的双引号和单引号

随机推荐

  1. Android(安卓)Application Architecture
  2. layout_gravity和gravity的区别
  3. 折叠式标题栏实现
  4. Android(安卓)安全和权限
  5. android:ADT 22.0.1 发布
  6. android之控件EditText学习
  7. Android 触屏事件处理_手势识别
  8. 简单安卓QQ登录界面
  9. android SQLite数据库存储数据
  10. 怎样成为一名Android开发者