Python类型转换

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





你可能感兴趣的:(python)