python中类型转换
1. 类型转换函数
函数 | 说明 |
---|---|
int(x) | 将x转换为一个整数 |
float(x) | 将x转换为一个浮点数 |
str(x) | 将x转换为一个字符串 |
2.类型转换示例代码
# int(x) 转换为整型
# float(x) 转换为浮点型
# str(x) 转换为字符串
a = 123 # 整型
# 将整型的a转换为字符串类型,再给a_str赋值
a_str = str(a)
print(type(a_str)) # 输出结果:<class 'str'>
print("a_str = %s" % a_str) # 输出结果:a_str = 123
b = "250" # 字符串类型
# 将字符串的b转换为整型,再给b_int赋值
b_int = int(b)
print(type(b_int)) # 输出结果:<class 'int'>
c = '3.14' # 字符串
c_float = float(c)
print(type(c_float)) # 输出结果:<class 'float'>```