【发布时间】:2016-09-23 01:50:00
【问题描述】:
我最近在 Python 3.5 中遇到了这个问题:
>>> flt = '3.14'
>>> integer = '5'
>>> float(integer)
5.0
>>> float(flt)
3.14
>>> int(integer)
5
>>> int(flt)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
int(flt)
ValueError: invalid literal for int() with base 10: '3.14'
这是为什么?它似乎应该返回3。我做错了什么,还是有充分的理由发生这种情况?
【问题讨论】:
-
重点:如果不赋值
float(flt)的结果,例如flt = float(flt),则转换后的值被丢弃。它不会就地更改它的参数(Python 没有与 C++ 传递引用等效的概念来允许这样做),因此int(flt)是在原始str上运行的,而不是float。基本上,int()与floats 配合得很好,但你没有给它float。
标签: python python-3.x floating-point int