类型转换是Python编程中的核心技能之一,掌握它能有效避免运行时错误并提升代码灵活性。以下是常见转换方式与技巧:
基础转换方法 🧾
- 隐式转换:自动完成,如
int + float
会返回float
- 显式转换
str() # 例:str(123) → "123" int() # 例:int("100") → 100 float() # 例:float("3.14") → 3.14
进阶技巧 🔍
- 多类型转换
bool(0) → False list("abc") → ['a','b','c']
- 自定义转换
使用__int__()
、__str__()
等魔术方法实现类实例的转换
常见错误避坑 ⚠️
- ❌
int("123a")
会抛出ValueError
- ✅ 使用
try-except
捕获异常:try: num = int(input) except ValueError: print("请输入有效数字")
了解更多Python数据类型操作 ➡️ 深入学习类型特性与应用