float('25') 有效,但 int('25.2') 不工作。为什么?

  • 本文关键字:工作 int 有效 float python
  • 更新时间 :
  • 英文 :

>>> float('25')
25.0
>>> int('25.2')
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
int('25.2')
ValueError: invalid literal for int() with base 10: '25.2'

为什么我在int('25.2')上得到错误,而在float('25')上没有得到错误?

Python试图通过将字符串转换为整数来防止您意外丢失小数点后的信息,而您应该将其转换为浮点数。

但是,它允许将浮点数转换为整数,因此,通过更明确的代码,您可以将带有小数点的字符串转换为整数:

>>> float('1.6')
1.6
>>> int('1.6')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1.6'
>>> int(1.6)
1
>>> int(float('1.6'))
1
>>> round(1.6)
2
>>> round(float('1.6'))
2
>>> round(float('1.2'))
1

请注意,int总是向下舍入,直接去掉小数部分,而round则舍入到最接近的整数。

最新更新