“21天好习惯”第一期-9

  • Post author:
  • Post category:其他


python——类型转化( int( )、str( )、float( ) )

int()

含义:将其他类型转换成整数类型

print('----------int()——将其它的类型转成int类型----------')
s1='128'
f1=98.7
s2='76.77'
ff=True
s3='hello'
print(type(s1),type(f1),type(s2),type(ff),type(s3))
print(int(s1),type(int(s1)))   #将str转成int类型,字符串为数字串
print(int(f1),type(int(f1)))   #float转成int类型,截取整数部分,舍掉小数部分
#print(int(s2),type(int(s2)))  将str转成int类型,报错,因为字符串为小数串
print(int(ff),type(int(ff)))
#print(int(s3),type(int(s3)))  将str转成int类型,字符串必须为数字串(整数),非数字串是不允许转换
'''
----------int()——将其它的类型转成int类型----------
<class 'str'> <class 'float'> <class 'str'> <class 'bool'> <class 'str'>
128 <class 'int'>
98 <class 'int'>
1 <class 'int'>
'''

str()

含义:将其他类型转换成字符串类型

print('------------str()——将其它类型转成str类型-----------')
a=10
b=198.8
c=False
print(type(a),type(b),type(c))
print(str(a),str(b),str(c),type(a),type(b),type(c))
'''
------------str()——将其它类型转成str类型-----------
<class 'int'> <class 'float'> <class 'bool'>
10 198.8 False <class 'int'> <class 'float'> <class 'bool'>
'''

float()

含义:将其他类型转换成浮点数类型

print('---------float()——将其它数据类型转成float类型--------------')
s1='128.98'
s2='76'
ff=True
s3='hello'
i=98
print(type(s1),type(s2),type(ff),type(s3),type(i))
print(float(s1),type(float(s1)))
print(float(s2),type(float(s2)))
print(float(ff),type(float(ff)))
#print(float(s3),type(float(s3)))   #字符串中的数据结构如果是非数字串,则不允许转换
print(float(i),type(float(i)))
'''
---------float()——将其它数据类型转成float类型--------------
<class 'str'> <class 'str'> <class 'bool'> <class 'str'> <class 'int'>
128.98 <class 'float'>
76.0 <class 'float'>
1.0 <class 'float'>
98.0 <class 'float'>
'''



版权声明:本文为weixin_51070720原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。