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

你可能感兴趣的:(学习)