Python-数据类型转换

数据类型转换

*为什么需要数据类型转换
将不同数据类型的数据拼接在一起
在这里插入图片描述

name='张三'
age=25

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=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)))

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)))   #将布尔类型转换为int类型
#print(int(s3),type(int(s3)))  #将str转成int类型时,字符串必须为数字串(整数),非数字串不允许转换

显示结果为:

<class 'str'> <class 'int'>
我叫张三 今年25-------------str()将其他类型转成str类型---------------
<class 'int'> <class 'float'> <class 'bool'>
10 198.8 False <class 'str'> <class 'str'> <class 'str'>
-------------int()将其他类型转成int类型---------------
<class 'str'> <class 'float'> <class 'str'> <class 'bool'> <class 'str'>
128 <class 'int'>
98 <class 'int'>
1 <class 'int'>
print('------------------float()函数,将其他数据类型转成float类型')
s1='128'
f1=98.7
s2='76.77'
ff=True
s3='Hello'
i=98
print(type(s1),type(f1),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 'float'> <class 'str'> <class 'bool'> <class 'str'> <class 'int'>
128.0 <class 'float'>
76.77 <class 'float'>
1.0 <class 'float'>
98.0 <class 'float'>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值