为什么需要数据类型转换
将不同数据类型的数据拼接在一起
当不同类型拼接在一起时,会产生错误
print('我叫'+name+',今年'+20+'岁了')
因此我们需要通过类型转换来解决问题
print('我叫'+name+',今年'+str(age)+'岁了')
此时会输出正确的结果
练习:
用str()将其他类型转换成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(str(a)),type(str(b)),type(str(c)))
结果发现都可以转换成字符串类型
用int()将其他类型转换成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))
#将str转成int类型,字符串为数字串
print(int(s1),type(int(s1)))
#将float转换为int类型,截取整数部分,舍掉小数部分
print(int(f1),type(int(f1)))
#将str转成int类型,报错,因为字符串为小数串
# print(int(s2),type(int(s2)))
print(int(ff),type(int(ff)))
#将str转换成int类型时,字符串必须为数字串(整数),非数字串不允许转换
#print(int(s3),type(int(s3)))
总结,当字符串为小数串,是非数字串是是无法转换为int类型的
会产生如下的错误
用float()将其他类型转换成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)))
注意:当字符串中为非数字串时将无法转换,会产生错误
s3 = 'hello'
print(float(s3),type(float(s3)))
int、str、float它们三种类型可以相互转换的,将通过int()、str()、float()三个函数
基础知识,请大家多多练习