6.1 隐式类型转换
在隐式类型转换中,Python 会自动将一种数据类型转换为另一种数据类型,不需要干预。
a = 123
b = 1.23
c = a + b
print("datatype of a:", type(a))
print("datatype of b:", type(b))
print("Value of c:", c)
print("datatype of c:", type(c))
结果:
datatype of a: <class 'int'>
datatype of b: <class 'float'>
Value of c: 124.23
datatype of c: <class 'float'>
6.2 显式类型转换
a = int(11)
b = int(2.3)
c = int("34")
print("a=",a)
print("b=",b)
print("c=",c)
结果:
a= 11
b= 2
c= 34
x = float(122)
y = float(2.2)
z = float("9")
w = float("4.8")
print(x)
print(y)
print(z)
print(w)
结果:
122.0
2.2
9.0
4.8
a = str("sss1")
b = str(32)
c = str(23.3)
print("a = ", a)
print("b = ", b)
print("c = ", c)
结果:
a = sss1
b = 32
c = 23.3