python字符串转整形异常
问题
在使用int("xx")转化字符串为整形时,如果字符串是float形式,这样转化会异常
int('3.0')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '3.0'
解决:
先转化为浮点型,在转化为整形
int(float('3.0'))
实例:
>>> int('3.0')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '3.0'
>>> int('3')
3
>>> int(float('3.0'))
3
>>> float('3')
3.0
>>>