数据类型转换方法
函数名 | 作用 | 注意事项 | 举例 |
---|
str() | 将其他数据类型转换成字符串 | 也可以用引号转换 | str(123),‘123’ |
int() | 将其他数据类型转换成整数 | 文字类和小数类字符串无法转换成整数; 浮点数转换成整数,抹零取整 | int(‘123’), int(9.8) |
float() | 将其他数据类型转换成浮点数 | 文字类无法转换成浮点数 | float(‘9.9’), float(9) |
str()
a = 10
b = 198.8
c = False
print(str(a), type(str(a)), str(b), type(str(b)), str(c), type(str(b)))
10 <class 'str'> 198.8 <class 'str'> False <class 'str'>
int()
s1 = '123'
f1 = 98.7
s2 = '76.77'
ff = True
s3 = 'hello'
print(int(s1), type(int(s1)))
print(int(f1), type(int(f1)))
# print(int(s2), type(int(s2))) # 小数类字符串转换成整数类型会报错
print(int(ff), type(int(ff)))
# print(int(s3), type(int(s3))) # 将str转换成int时, 字符串必须为整数串
123 <class 'int'>
98 <class 'int'>
1 <class 'int'>
float()
s1 = '123'
f1 = 98.7
s2 = '76.77'
ff = True
s3 = 'hello'
print(float(s1), type(float(s1)))
print(float(f1), type(float(f1)))
print(float(s2), type(float(s2)))
print(float(ff), type(float(ff)))
123.0 <class 'float'>
98.7 <class 'float'>
76.77 <class 'float'>
1.0 <class 'float'>