数据类型转换

将不同类型的数据类型整合到一起

将str()将其他类型转化为str类型

print(type(name), type(age))#说明name与age的数据类型不同
#print('我叫'+name+'今年,'+age+'岁')#当将str类型进行链接时,报错,解决方案,类型转换
print('我叫'+name+'今年,'+str(age)+'岁')#将int类型通过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))

 运行结果

print('------------------------int()将其他类型转换为int类型-------------------------')
print('------------------------int()将其他类型转换为int类型-------------------------')
s1='123'
f1=87.3
s2='34.98'
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(s1)))#将float转换为int类型,就取整数部分,舍掉小数部分
#print(int(s2), type(int(s2)))#将str转化为int类型,报错,因为字符串为小数串
print(int(ff), type(int(ff)))
#print(int(s3), type(int(s3)))报错将str的转换为时,字符串必须为数字串

 运行结果

 

print('---------------------------------float()函数,将其他类型的函数转化为float类型')
print('---------------------------------float()函数,将其他类型的函数转化为float类型')
s1='123'
f1=87.3
s2='34.98'
ff=True
s3='hello'
i=778
print(type(s1),  type(f1),  type(s2),  type(ff),  type(s3),  type(s3))
print(float(s1), type(float(s1)))
print(float(f1), type(float(s1)))
print(float(s2), type(float(s2)))
print(float(ff), type(float(ff)))
#print(float(s3), float(int(s3)))#我们这如果字符串中的数据将是非数字串则不允许转换


运行结果

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值