Python类型转换
Python 支持显式类型转换和隐式类型转换,理解转换规则避免精度丢失。
显式类型转换
int() 转换
Python
# 浮点数转整数(截断)
print(int(3.14)) # 3
print(int(-3.14)) # -3
# 字符串转整数
print(int("10")) # 10
# 布尔转整数
print(int(True)) # 1
print(int(False)) # 0
# 进制转换
print(int("10", 2)) # 2(二进制)
print(int("10", 16)) # 16(十六进制)
float() 转换
Python
# 整数转浮点数
print(float(10)) # 10.0
# 字符串转浮点数
print(float("3.14")) # 3.14
print(float("1e3")) # 1000.0
# 布尔转浮点数
print(float(True)) # 1.0
str() 转换
Python
# 整数转字符串
print(str(10)) # '10'
# 浮点数转字符串
print(str(3.14)) # '3.14'
# 布尔转字符串
print(str(True)) # 'True'
# 对象转字符串
print(str([1, 2, 3])) # '[1, 2, 3]'
bool() 转换
Python
# 整数转布尔
print(bool(1)) # True
print(bool(0)) # False
print(bool(-1)) # True(非零为 True)
# 浮点数转布尔
print(bool(0.0)) # False
print(bool(3.14)) # True
# 字符串转布尔
print(bool("")) # False(空字符串)
print(bool("hello")) # True
# 空容器转布尔
print(bool([])) # False
print(bool({})) # False
print(bool(None)) # False
隐式类型转换
数值运算中的隐式转换
Python
# 整数 + 浮点数 → 浮点数
print(10 + 3.14) # 13.14(int 转 float)
# 整数运算结果为整数
print(10 + 5) # 15(int)
# 除法默认返回浮点数
print(10 / 2) # 5.0(float)
print(10 / 3) # 3.333...(float)
比较运算中的隐式转换
Python
# 不同类型比较
print(10 == 10.0) # True(隐式转换)
print(1 == True) # True
print(0 == False) # True
不推荐直接比较不同类型,可能产生意外结果。
精度问题
浮点数转整数丢失精度
Python
value = 3.99
result = int(value) # 3(直接截断,非四舍五入)
# 四舍五入方法
print(round(value)) # 4
print(int(round(value))) # 4
大浮点数转换
Python
large = 1.23456789e10
print(int(large)) # 12345678900
# 可能超出预期精度
large = 1e20
print(int(large)) # 100000000000000000000
转换失败处理
ValueError 示例
Python
# 非数字字符串转整数会失败
# int("hello") # ValueError
# 非数字字符串转浮点数会失败
# float("abc") # ValueError
# 安全转换
def safe_int(value):
try:
return int(value)
except ValueError:
return None
print(safe_int("10")) # 10
print(safe_int("hello")) # None
类型检查
Python
def convert_to_int(value):
if isinstance(value, (int, float)):
return int(value)
if isinstance(value, str) and value.isdigit():
return int(value)
return None
print(convert_to_int(10)) # 10
print(convert_to_int("10")) # 10
print(convert_to_int("hello")) # None
列表/元组转换
list() 和 tuple()
Python
# 字符串转列表
print(list("hello")) # ['h', 'e', 'l', 'l', 'o']
# 元组转列表
print(list((1, 2, 3))) # [1, 2, 3]
# 列表转元组
print(tuple([1, 2, 3])) # (1, 2, 3)
# 列表转集合
print(set([1, 2, 2, 3])) # {1, 2, 3}
类型转换函数对比
| 函数 | 输入类型 | 输出类型 | 示例 |
|---|---|---|---|
| int() | float, str, bool | int | int(3.14) → 3 |
| float() | int, str, bool | float | float(10) → 10.0 |
| str() | 任意 | str | str(10) → '10' |
| bool() | 任意 | bool | bool(0) → False |
| list() | str, tuple | list | list("abc") → ['a', 'b', 'c'] |
| tuple() | list, str | tuple | tuple([1,2]) → (1, 2) |
要点总结
- 显式转换使用 int()、float()、str()、bool()
- int() 转换浮点数会截断,不四舍五入
- 隐式转换发生在数值运算中
- 非法转换会抛出 ValueError
- 转换前做好类型检查或异常处理
📝 发现内容有误?点击此处直接编辑