Python类型转换
1、整数字符串转浮点数
>>> float(3)3.0>>> float('4.2')4.2
2、整数浮点数转字符串
>>> str(4)'4'>>> str(4.3345)'4.3345'
3、浮点数字符串转整数
>>> int('5')5>>> int(5.89)5>>> round(5.89)6>>> round(5.5)6>>> round(4.5)4
int表示向下取整,round表示四舍五入,但当round处理.5的情况时,Python采用银行家圆整的方式,即:将.5部分圆整到最接近的偶数
4、当字符串转整数或者浮点数时,如果字符串不符合相应的类型,python将不会执行转换并出现错误信息
>>> int('5.3')Traceback (most recent call last):File "<pyshell#20>", line 1, in <module>int('5.3')ValueError: invalid literal for int() with base 10: '5.3'>>>
浙公网安备 33010602011771号