为什么需要数据类型转换?
将不同数据类型的数据拼接在一起
name='张三'
age=20
print(type(name),type(age))#说明name与age的数据类型不相同
print('我叫'+name+'今年,'+str(age)+'岁')#将int类型通过str()函数转成了str类型
#结果
<class 'str'> <class 'int'>
我叫张三今年,20岁
name='张三'
age=20
print(type(name),type(age))#说明name与age的数据类型不相同
print('我叫'+name+'今年,'+age+'岁')#当将str与int类型进行连接时,报错,解决方案,类型转换
#结果
print('我叫'+name+'今年,'+age+'岁')#当将str与int类型进行连接时,报错,解决方案,类型转换
TypeError: can only concatenate str (not "int") to str
16.类型转换_float()函数
数据类型转换
为什么需要数据类型转换?
讲不同数据类型的数据拼接在一起
s1='13.14'
s2='52'
l1=True
s3='hello'
i=100
print(type(s1),type(s2),type(l1),type(s3),type(i))
print(float(s1),type(float(s1)))
print(float(s2),type(float(s2)))
print(float(l1),type(float(l1)))
#print(float(s3),type(float(s3))) #字符串中的数据如果是非数字串,则不允许转换
print(float(i),type(float(i)))
#结果
<class 'str'> <class 'str'> <class 'bool'> <class 'st