Python 3 数据类型转换(Type Conversion)详解
                           
天天向上
发布: 2025-03-14 21:52:09

原创
208 人浏览过

Python 3 提供了丰富的数据类型,并支持 显式转换(Explicit Conversion)隐式转换(Implicit Conversion)


1. 隐式类型转换(Implicit Type Conversion)

隐式转换是 Python 自动 进行的数据类型转换,通常发生在数值运算中。

示例

a = 5      # int
b = 2.5    # float
c = a + b  # Python 自动将 int 转换为 float
print(c)   # 7.5
print(type(c))  # <class 'float'>

常见的隐式转换

  • int → float
  • int → complex
  • bool → int
  • bool → float
x = 10     # int
y = 3 + 4j  # complex
z = x + y  # int 自动转换为 complex
print(z)   # (13+4j)
print(type(z))  # <class 'complex'>

2. 显式类型转换(Explicit Type Conversion)

显式转换需要使用 Python 提供的内置函数,如:

  • int()
  • float()
  • complex()
  • str()
  • list()
  • tuple()
  • set()
  • dict()
  • bool()

2.1 数值转换

(1)整数(int)转换

print(int(3.14))  # 3
print(int("10"))  # 10
print(int(True))  # 1
print(int(False)) # 0

错误转换

# print(int("3.14"))  # ValueError: invalid literal for int()

(2)浮点数(float)转换

print(float(10))  # 10.0
print(float("3.14"))  # 3.14
print(float(True))  # 1.0
print(float(False)) # 0.0

(3)复数(complex)转换

print(complex(10))  # (10+0j)
print(complex(3.14))  # (3.14+0j)
print(complex("2+3j"))  # (2+3j)

2.2 字符串(str)转换

print(str(10))  # '10'
print(str(3.14))  # '3.14'
print(str(True))  # 'True'
print(str(None))  # 'None'

2.3 布尔值(bool)转换

布尔值 TrueFalse 本质上是 10,以下规则适用于 bool()

  • 数值 0False
  • 数值非 0True
  • 空字符串 ""False
  • 非空字符串True
  • NoneFalse
  • 空容器([], {}, ())False
  • 非空容器True
print(bool(0))  # False
print(bool(3.14))  # True
print(bool(""))  # False
print(bool("Hello"))  # True
print(bool([]))  # False
print(bool([1, 2, 3]))  # True
print(bool(None))  # False

2.4 序列类型转换

(1)列表(list)转换

print(list("hello"))  # ['h', 'e', 'l', 'l', 'o']
print(list((1, 2, 3)))  # [1, 2, 3]
print(list({1, 2, 3}))  # [1, 2, 3]

(2)元组(tuple)转换

print(tuple("hello"))  # ('h', 'e', 'l', 'l', 'o')
print(tuple([1, 2, 3]))  # (1, 2, 3)
print(tuple({1, 2, 3}))  # (1, 2, 3)

(3)集合(set)转换

print(set("hello"))  # {'h', 'e', 'o', 'l'}
print(set([1, 2, 2, 3]))  # {1, 2, 3}
print(set((1, 2, 2, 3)))  # {1, 2, 3}

(4)字典(dict)转换

字典的转换要求特殊格式:

print(dict([("name", "Alice"), ("age", 25)]))  # {'name': 'Alice', 'age': 25}

3. 进阶:JSON 与数据类型转换

Python 提供 json 模块,用于 JSON 和 Python 数据类型的相互转换。

import json

data = {"name": "Alice", "age": 25, "city": "Beijing"}
json_str = json.dumps(data)  # Python dict 转 JSON 字符串
print(json_str)  # '{"name": "Alice", "age": 25, "city": "Beijing"}'

python_dict = json.loads(json_str)  # JSON 字符串转 Python 字典
print(python_dict)  # {'name': 'Alice', 'age': 25, 'city': 'Beijing'}

4. 类型转换总结

原类型 → 目标类型int()float()str()bool()list()tuple()set()
int
float
str❌(仅限整数)✅(仅限数字)
bool
list
tuple
set

更多详细内容请关注其他相关文章😃

发表回复 0

Your email address will not be published. Required fields are marked *