python学习(3)数据类型转换

str()函数:

将其他数据转换成为字符串

注意事项:

也可以用引号转换

int()函数:

将其他数据类型转换为整数

注意事项:

1.文字类和小数类字符串无法转换成整数

2.浮点数转化成为整数:抹掉小数位,保留整数位

float()函数:

将其他数据类型转换为浮点数

注意事项:

1.文字类无法转换为浮点数

2.整数转换为浮点数,小数部分为.0000

具体代码转换如下:

name='张三'
age=20

print(type(name),type(age))#说明name和age的数据类型不同
#print('我叫'+name+'今年'+age+'岁')#当与str类型和int类型进行连接时,会发生报错,解决方案,类型转换
print('我叫'+name+'今年'+str(age)+'岁')#将int类型通过str()函数转换成为了str类型

print('-----------------str()将其他类型转换成str类型------------')
a=10
b=12.2
c=False
print(type(a),type(b),type(c))
print(str(a),str(b),str(c),type(a),type(b),type(c))

print('----------------int()将其他函数类型转换成int类型---------------')
s1='1258'
f1=98.7
s2='75.36'
ff=False
s3='hello world!'
print(type(s1),type(s2),type(f1),type(ff),type(f1))
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(ff))) #将str转换成int类型时,字符串必须为数字串(整数),非数字串不允许转换

print('-------------------float()函数,将其他数据类型转换成float类型')
s1='1258.22'
s2='75.36'
ff=False
s3='hello world!'
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)))

学习视频地址:

https://www.bilibili.com/video/BV1wD4y1o7AS?spm_id_from=333.337.search-card.all.clickicon-default.png?t=M3K6https://www.bilibili.com/video/BV1wD4y1o7AS?spm_id_from=333.337.search-card.all.click

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值