python常见的数据类型转换str() int() float()使用

     

为什么需要数据类型转换呢?
将不同的数据的数据拼接在一起

str()是将其他数据类型转换成字符串,也可以引号转换,str(123)等价于’123’

int()是将其他数据类型转换成整数:
注意:
1、文字类和小数类字符串,无法转换成整数
2、浮点数转换成整数,小数部分舍掉,只要整数部分
例如:
int(‘123’)=123
int(‘9.8’)=9

float()是将其他数据类型转换成浮点数
注意:
1、文字类无法转换成浮点型;
2、整数转换成浮点数,末尾.0
例如:
float(‘9.9’)=9.9
float(9)=9.0

 

复制代码
name='张三'
age=20
print(type(name),type(age))    #说明name和age数据类型不相同
#print('我叫'+name+'今年'+age+'岁')  #当将数据类型不相同进行拼接时,就会报错,解决方案,类型转换
print('我叫'+name+','+'今年'+str(age)+'')#将int的类型转换成str类型,进行拼接就不会报错了

print('---------str()将其他类型转换成str类型--------------------')
a=19
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'
f3=True
s3='hello'
print(type(s1),type(f1),type(s2),type(f3),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(f3),type(int(f3)))   #
#print(int(s3),type(int(s3)))    #将str转成int类型时,字符串必须是不带小数的数字串

print('---------------float(),将其他类型转成float类型----------------')
s1='128.98'
s2='76'
f3=True
s3='hello'
i=98
print(type(s1),type(s2),type(f3),type(s3),type(i))
print(float(s1),type(float(s1)))
print(float(s2),type(float(s2)))
print(float(f3),type(float(f3)))
#print(float(s3),type(float(s3)))  #z字符串中的数据如果是非字符串,则不允许转换
print(float(i),type(float(i)))
复制代码

运行结果:
<class ‘str’> <class ‘int’>
我叫张三,今年20岁
---------str()将其他类型转换成str类型--------------------
<class ‘int’> <class ‘float’> <class ‘bool’>
19 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’>
---------------float(),将其他类型转成float类型----------------
<class ‘str’> <class ‘str’> <class ‘bool’> <class ‘str’> <class ‘int’>
128.98 <class ‘float’>
76.0 <class ‘float’>
1.0 <class ‘float’>
98.0 <class ‘float’> 

posted @   菜鸡一枚QAQ  阅读(2310)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示