脚本宝典收集整理的这篇文章主要介绍了python数据类型转换,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
数据类型转换
函数名 | 作用 | 注意事项 | 举例 |
str() | 将其数据他类型转为字符串 | 也可用引号转换 |
str(123) '123' |
int() | 将其他数据类型转为整数 |
1,文字类和小数类字符串,无法转化为整数 2,浮点数转化为整数,抹零取整 |
int('123') int(9.8) |
float() | 将其他数据类型转为浮点数 |
1,文字类无法转为整数 2,整数转为浮点数,末尾为.0 |
float('9.9') float(9) |
name='小强' age=17 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=10.1 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类型------') a1='17' a2=16.2 a3='18.99' a4=True a5='hello' print(type(a1),type(a2),type(a3),type(a4),type(a5)) print(int(a1),type(int(a1))) #将str转换为int类型,字符串为小数串 print(int(a2),type(int(a2))) #float换为int类型,截取整数部分,舍掉小数部分 #print(int(a3),type(int(a3))) #将str转换为int类型时,报错,因为字符串为小数串 print(int(a4),type(int(a4))) #print(int(a5),type(int(a5))) #将str转换为int类型时,字符串必须为数字串(整数)非数字串不可以转换 print('-------float()将其他类型转换成float类型------') b1='17.1' b2='18' b3=True b4='hello' b5=9 print(type(b1),type(b2),type(b3),type(b4),type(b5)) print(float(b1),type(float(b1))) print(float(b2),type(float(b2))) print(float(b3),type(float(b3))) #print(float(b4),type(float(b4))) #字符串中数据如果是非字符串,则不可以转换 print(float(b5),type(float(b5)))
运行结果:
以上是脚本宝典为你收集整理的python数据类型转换全部内容,希望文章能够帮你解决python数据类型转换所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。