# 作 者:要努力,努力,再努力
# 开发日期:2022/4/10 21:40
name = '张三'
age = 20
print(type(name), type(age)) # name与age的数据类型不同
# print('我叫'+name+'今年,'+age+'岁') # 报错!name与age的数据类型不同而将他们直接连接,会报错。
解决方案:类型转换
print('我叫' + name + '今年,' + str(age) + '岁') # 将int类型通过str()函数转成str类型
print("=========str()将其他的数据类型转成str类型=============")
a = 10
b = 98.8
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 = '128'
f1 = 98.7
s2 = '76.77'
f2 = True
s3 = 'Hello'
print(type(s1), type(f1), type(s2), type(f2), type(s3))
print(int(s1), type(int(s1))) # 将str转成int类型,字符串为整数串,
print(int(f1), type(int(f1))) # 只截取整数部分,舍去小数部分
# print(int(s2), type(int(s2))) # 将str转成int类型,报错,字符串为小数串
print(int(f2), type(int(f2))) # 将bool转成int类型
# print(int(s3), type(int(s3))) # 将str转成int类型,报错,因为字符串必须为整数数字串
print("=========float()将其他的数据类型转成float类型=============")
s1 = '128.98'
s2 = '76'
f2 = True
s3 = 'Hello'
i = 98
print(type(s1), type(s2), type(f2), type(s3), type(i))
print(float(s1), type(float(s1)))
print(float(s2), type(float(s2)))
print(float(f2), type(float(f2)))
# print(float(s3), type(float(s3))) # 将str转成float类型,字符串必须为数字串,
print(float(i), type(float(i)))
运行结果:
总结:
1. str() 函数将其他类型转成 str 类型,都是可以的。
2. int() 函数将其他类型转成 int 类型,注意将字符串类型str转成int类型,该字符串必须整数串。
3. float() 函数将其他类型转成 float 类型,注意将字符串类型str转成float类型,该字符串必须数字串。
【Python 的类型转换 就是这些~如有不对之处,欢迎批评指正。
】
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)