python - 数据类型转换

138 阅读3分钟

在 Python 中,数据类型转换(Type Casting/Conversion)是指将一种数据类型(如整数、字符串等)转换为另一种数据类型。Python 支持隐式转换(自动完成)和显式转换(手动调用函数)。以下是详细的分类和示例:


一、隐式类型转换

Python 会自动完成某些类型的转换(例如数值间的运算):

python
a = 10      # int
b = 3.5     # float
c = a + b   # 自动将 a 转为 float,结果为 13.5(float)
print(type(c))  # <class 'float'>

二、显式类型转换

通过内置函数手动转换类型,常见场景如下:

1. 转换为整数 int()

python
# 字符串 → 整数
num_str = "123"
num_int = int(num_str)  # 123
print(type(num_int))   # <class 'int'>
 
# 浮点数 → 整数(截断小数部分)
float_num = 3.9
int_num = int(float_num)  # 3

2. 转换为浮点数 float()

python
# 字符串 → 浮点数
pi_str = "3.14"
pi_float = float(pi_str)  # 3.14
 
# 整数 → 浮点数
num = 5
float_num = float(num)    # 5.0

3. 转换为字符串 str()

python
# 任何类型 → 字符串
num = 42
str_num = str(num)        # "42"
 
boolean = True
str_bool = str(boolean)   # "True"

4. 转换为布尔值 bool()

  • False 值00.0""(空字符串)、None[](空列表)、{}(空字典)等。
  • True 值:其他非空或非零值。
python
print(bool(0))      # False
print(bool("Hi"))   # True
print(bool([]))     # False

5. 转换为列表 list()

python
# 字符串 → 字符列表
s = "hello"
list_s = list(s)  # ['h', 'e', 'l', 'l', 'o']
 
# 元组 → 列表
tuple_data = (1, 2, 3)
list_data = list(tuple_data)  # [1, 2, 3]

6. 转换为元组 tuple()

python
# 列表 → 元组
list_data = [1, 2, 3]
tuple_data = tuple(list_data)  # (1, 2, 3)

7. 转换为集合 set()

  • 去重并转换为无序集合:
python
list_with_duplicates = [1, 2, 2, 3]
unique_set = set(list_with_duplicates)  # {1, 2, 3}

8. 转换为字典 dict()

  • 需满足键值对结构(如嵌套列表或元组):
python
pairs = [("a", 1), ("b", 2)]
dict_data = dict(pairs)  # {'a': 1, 'b': 2}

三、特殊场景处理

1. 字符串与数字的转换

  • 字符串转数字:必须为合法数字字符串,否则抛出 ValueError

    python
    int("123")    # 成功 → 123
    int("12a")    # 报错: ValueError
    
  • 数字转字符串:任何数字均可转换。

    str(3.14)     # "3.14"
    

2. 复杂类型转换

  • 列表转字符串:需手动拼接(如 join())。

    words = ["Hello", "World"]
    sentence = " ".join(words)  # "Hello World"
    
  • JSON 字符串转字典:使用 json 模块。

    import json
    json_str = '{"name": "Alice", "age": 25}'
    dict_data = json.loads(json_str)  # {'name': 'Alice', 'age': 25}
    

3. 自定义对象转换

  • 通过实现 __str__() 或 __int__() 等魔术方法控制转换行为:

    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age
        
        def __str__(self):
            return f"Person(name={self.name}, age={self.age})"
        
        def __int__(self):
            return self.age
     
    p = Person("Bob", 30)
    print(str(p))   # "Person(name=Bob, age=30)"
    print(int(p))   # 30
    

四、常见错误与注意事项

  1. 无效转换

    int("hello")  # ValueError: invalid literal for int()
    
  2. 精度丢失

    int(3.9)      # 3(直接截断,不四舍五入)
    
  3. 类型检查:转换前建议用 isinstance() 验证类型。

    if isinstance(input_str, str):
        num = int(input_str)
    

五、总结

转换目标常用函数示例
整数int()int("42") → 42
浮点数float()float("3.14") → 3.14
字符串str()str(100) → "100"
布尔值bool()bool(1) → True
列表list()list("abc") → ['a','b','c']
元组tuple()tuple([1, 2]) → (1, 2)
集合set()set([1, 1, 2]) → {1, 2}
字典dict()dict([("a", 1)]) → {'a': 1}

关键点

  • 显式转换需确保数据格式合法(如字符串必须是数字格式才能转 int)。
  • 隐式转换通常发生在数值运算中(如 int + float → float)。
  • 复杂转换(如 JSON、自定义对象)需借助模块或魔术方法。