全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-19 6 分钟 ✍️ juanwangdev

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, boolintint(3.14) → 3
float()int, str, boolfloatfloat(10) → 10.0
str()任意strstr(10) → '10'
bool()任意boolbool(0) → False
list()str, tuplelistlist("abc") → ['a', 'b', 'c']
tuple()list, strtupletuple([1,2]) → (1, 2)

要点总结

  1. 显式转换使用 int()、float()、str()、bool()
  2. int() 转换浮点数会截断,不四舍五入
  3. 隐式转换发生在数值运算中
  4. 非法转换会抛出 ValueError
  5. 转换前做好类型检查或异常处理

📝 发现内容有误?点击此处直接编辑

← 上一篇 Python数值运算与精度
下一篇 → Python 成员运算符
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库