python 把带小数的浮点型字符串转换为整数的解决方案

以下内容在python中完全可以接受:

  1. 将整数的字符串表示形式传递给 int
  2. 将float的字符串表示形式传递给 float

但是,如果你将float型的字符串传递给int将会得到错误。

>>> int('5')
5
>>> float('5.0')
5.0
>>> float('5')
5.0
>>> int(5.0)
5
>>> float(5)
5.0
>>> int('5.0')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.0'
>>> int(float('5.0'))
posted @ 2019-07-11 15:32  哦摩西罗伊  阅读(25000)  评论(0编辑  收藏  举报