Python 类型转换

类型转换

你可以使用 int()float()complex() 方法来进行类型转换:

实例

从一种类型转换到另一种类型:

x = 1 # int
y = 2.8 # float
z = 1j # complex

# 从 int 转换为 float:
a = float(x)

# 从 float 转换为 int:
b = int(y)

# 从 int 转换为 complex:
c = complex(x)

print(a)
print(b)
print(c)

print(type(a))
print(type(b))
print(type(c))

亲自试一试

注意:你无法将复数转换为其他数字类型。