- 简介
- 隐式类型转换
- 显式类型转换
偶尔我们可能会对数据内置的类型转换,作数据类型转换的时候,通常情况下需要将数据类型作为函数名。
数据类型转换一般分为显式与隐式两种。
隐式转换系统会自动的转换成另一种数据类型,不需要我们去人为干预。
以下实例会自动的转换成浮点数:
#!/usr/bin/python3
i_dtcoud = 123
f_dtcloud = 1.23
new_dtcloud = i_dtcoud + f_dtcloud
print("datatype of i_dtcoud:",type(i_dtcoud))
print("datatype of f_dtcloud:",type(f_dtcloud))
print("Value of new_dtcloud:",new_dtcloud)
print("datatype of new_dtcloud:",type(new_dtcloud))
显式类型转换
除了自动的隐式转换,我们也可以手动进行显示转换。各位读者可以运用像是 int()、float()、str() 等预定义函数来进行显式类型转换。
以int()为例:
x = int(1) # x 输出结果为 1
y = int(2.8) # y 输出结果为 2
z = int("3") # z 输出结果为 3
print(x, y, z)
整型和字符串的运算也可以用强制转换完成:
i_dtcoud = 123
str_dtcloud = "456"
print("i_dtcoud 数据类型为:",type(i_dtcoud))
print("类型转换前,str_dtcloud 数据类型为:",type(str_dtcloud))
str_dtcloud = int(str_dtcloud) # 强制转换为整型
print("类型转换后,str_dtcloud 数据类型为:",type(str_dtcloud))
sum_dtcloud = i_dtcoud + str_dtcloud
print("i_dtcoud 与 str_dtcloud 相加结果为:",sum_dtcloud)
print("sum 数据类型为:",type(sum_dtcloud))



