python 中数据类型转换

数据类型转换是指将一种数据类型转换为另一种数据类型。Python 支持隐式类型转换 (自动)和显式类型转换(手动)两种方式。

一、转换的类型

转换类型 关键字 说明
整数 int() 转换为整型
浮点数 float() 转换为浮点型
字符串 str() 转换为字符串
布尔值 bool() 转换为布尔型
列表 list() 转换为列表
元组 tuple() 转换为元组
集合 set() 转换为集合
字典 dict() 转换为字典
复数 complex() 转换为复数

二、数字类型转换

1. 整数转换 -int()

复制代码
# 字符串 → 整数
print(int("123"))        # 123
print(int("  456  "))    # 456(自动去除空白)
print(int("-789"))       # -789

# 浮点数 → 整数(截断,不是四舍五入)
print(int(3.14))         # 3
print(int(3.99))         # 3
print(int(-3.14))        # -3

# 布尔值 → 整数
print(int(True))         # 1
print(int(False))        # 0

# 进制转换
print(int("FF", 16))     # 255(十六进制)
print(int("1010", 2))    # 10(二进制)
print(int("17", 8))      # 15(八进制)
print(int("10", 10))     # 10(十进制)

# 转换失败的情况
# int("123a")           # ValueError
# int("12.34")          # ValueError(不能直接转)

2. 浮点数转换 -float()

复制代码
# 整数 → 浮点数
print(float(42))         # 42.0
print(float(-10))        # -10.0

# 字符串 → 浮点数
print(float("3.14"))     # 3.14
print(float("  -2.5 "))  # -2.5
print(float("1e-3"))     # 0.001(科学计数法)
print(float("inf"))      # inf(无穷大)
print(float("nan"))      # nan(非数字)

# 布尔值 → 浮点数
print(float(True))       # 1.0
print(float(False))      # 0.0

# float("abc")           # ValueError

3. 复数转换 -complex()

复制代码
# 整数/浮点数 → 复数
print(complex(3))        # (3+0j)
print(complex(3.14))     # (3.14+0j)

# 字符串 → 复数
print(complex("3+4j"))   # (3+4j)
print(complex("5-2j"))   # (5-2j)

# 指定实部和虚部
print(complex(2, 3))     # (2+3j)
print(complex(3.14, 2.5))  # (3.14+2.5j)

# complex("abc")         # ValueError

4. 布尔值转换 -bool()

复制代码
# 假值(转换为 False)
print(bool(0))           # False
print(bool(0.0))         # False
print(bool(""))          # False
print(bool([]))          # False
print(bool(()))          # False
print(bool({}))          # False
print(bool(set()))       # False
print(bool(None))        # False

# 真值(转换为 True)
print(bool(1))           # True
print(bool(-1))          # True
print(bool(3.14))        # True
print(bool("Hello"))     # True
print(bool([1, 2]))      # True
print(bool({"a": 1}))    # True

三、序列类型转换

1. 字符串转换 -str()

复制代码
# 数字 → 字符串
print(str(123))          # "123"
print(str(3.14))         # "3.14"
print(str(True))         # "True"

# 序列 → 字符串
print(str([1, 2, 3]))    # "[1, 2, 3]"
print(str((1, 2, 3)))    # "(1, 2, 3)"
print(str({"a": 1}))     # "{'a': 1}"

# 自定义对象
class Person:
    def __init__(self, name):
        self.name = name
    
    def __str__(self):
        return f"Person({self.name})"

p = Person("Alice")
print(str(p))            # Person(Alice)

2. 列表转换 -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]

# 字典 → 列表(只转换键)
print(list({"a": 1, "b": 2}))  # ['a', 'b']

# 范围 → 列表
print(list(range(5)))    # [0, 1, 2, 3, 4]

# 可迭代对象 → 列表
print(list(map(str, [1, 2, 3])))  # ['1', '2', '3']

3. 元组转换 -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)

# 字典 → 元组(只转换键)
print(tuple({"a": 1, "b": 2}))  # ('a', 'b')

4. 集合转换 -set()

复制代码
# 字符串 → 集合(自动去重)
print(set("Hello"))      # {'H', 'e', 'l', 'o'}

# 列表 → 集合(自动去重)
print(set([1, 2, 2, 3])) # {1, 2, 3}

# 元组 → 集合
print(set((1, 2, 2, 3))) # {1, 2, 3}

# 字典 → 集合(只转换键)
print(set({"a": 1, "b": 2}))  # {'a', 'b'}

5. 冻结集合转换 -frozenset()

复制代码
# 创建不可变集合
fs = frozenset([1, 2, 2, 3])
print(fs)                # frozenset({1, 2, 3})

# 字符串 → 冻结集合
fs2 = frozenset("Hello")
print(fs2)               # frozenset({'H', 'e', 'l', 'o'})

# 支持所有集合操作,但不能修改
# fs.add(4)              # AttributeError

四、字典转换 dict()

1. 创建字典的方式

复制代码
# 从键值对列表创建
pairs = [("name", "Alice"), ("age", 25)]
print(dict(pairs))       # {'name': 'Alice', 'age': 25}

# 从关键字参数创建
print(dict(name="Bob", age=30))  # {'name': 'Bob', 'age': 30}

# 从两个列表创建
keys = ["name", "age"]
values = ["Charlie", 35]
print(dict(zip(keys, values)))  # {'name': 'Charlie', 'age': 35}

# 从字典推导式创建
squares = {x: x**2 for x in range(5)}
print(squares)           # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# 可迭代对象(每个元素是键值对)
items = [("a", 1), ("b", 2)]
print(dict(items))       # {'a': 1, 'b': 2}

2. 使用 dict() 转换的限制

复制代码
# 不能直接转换字符串
# dict("abc")            # TypeError

# 不能直接转换列表
# dict([1, 2, 3])        # TypeError

# 必须是键值对形式
valid_pairs = [(1, 'a'), (2, 'b')]
print(dict(valid_pairs)) # {1: 'a', 2: 'b'}

五、隐式类型转换

Python 在某些运算中会自动进行类型转换。

1. 数字类型自动提升

复制代码
# int → float
result = 3 + 3.14        # 6.14(int 自动转为 float)

# bool → 数字
print(True + 1)          # 2(True 转为 1)
print(False + 1)         # 1(False 转为 0)

# int → complex
c = 3 + 2j
print(5 + c)             # (8+2j)

2. 在比较运算中

复制代码
# 数字比较
print(3 == 3.0)          # True(类型不同但值相等)

# 字符串与数字不能隐式转换
# print("3" + 5)         # TypeError

六、常用转换模式

1. 字符串 ↔ 字节串

复制代码
# 字符串 → 字节串
text = "你好"
bytes_data = text.encode('utf-8')
print(bytes_data)        # b'\xe4\xbd\xa0\xe5\xa5\xbd'

# 字节串 → 字符串
decoded = bytes_data.decode('utf-8')
print(decoded)           # 你好

# 其他编码
text.encode('gbk')       # GBK 编码
text.encode('ascii', errors='ignore')  # 忽略无法编码的字符

2. 列表 ↔ 字符串

复制代码
# 列表 → 字符串
chars = ['a', 'b', 'c']
print(''.join(chars))    # abc
print(','.join(chars))   # a,b,c

# 字符串 → 列表
s = "a,b,c"
print(s.split(','))      # ['a', 'b', 'c']

3. 进制转换

复制代码
# 十进制 → 其他进制
num = 255
print(bin(num))          # 0b11111111(二进制)
print(oct(num))          # 0o377(八进制)
print(hex(num))          # 0xff(十六进制)

# 其他进制 → 十进制
print(int('11111111', 2))  # 255
print(int('377', 8))       # 255
print(int('ff', 16))       # 255

4. ASCII 码转换

复制代码
# 字符 → ASCII 码
print(ord('A'))          # 65
print(ord('中'))         # 20013

# ASCII 码 → 字符
print(chr(65))           # 'A'
print(chr(20013))        # '中'

# 应用:大小写转换
def toggle_case(char):
    if 'a' <= char <= 'z':
        return chr(ord(char) - 32)
    elif 'A' <= char <= 'Z':
        return chr(ord(char) + 32)
    return char

print(toggle_case('a'))  # 'A'
print(toggle_case('Z'))  # 'z'

汇总

转换函数 输入类型 输出类型 常见用途
int() 数字、数字字符串 整数 用户输入处理
float() 数字、数字字符串 浮点数 计算、货币
str() 任意类型 字符串 输出、日志
bool() 任意类型 布尔值 条件判断
list() 可迭代对象 列表 数据转换
tuple() 可迭代对象 元组 不可变序列
set() 可迭代对象 集合 去重
dict() 键值对序列 字典 结构化数据
相关推荐
呱呱复呱呱2 小时前
Django CBV 源码解读:一个请求是怎么找到你的 get() 方法的
python·django
曲幽6 小时前
刚部署的 LibreTranslate 频频翻车?我掏出了 20 年前的 StarDict 词典,用 FastAPI 搭了个本地词典翻译 API
python·fastapi·web·translate·goldendict·libretranslate·stardict·pystardict
荣码7 小时前
用Streamlit给AI应用套个界面,10行代码出Web页面
java·python
兵慌码乱16 小时前
基于Python+PyQt5+SQLite的药房管理系统实现:事务一致性与界面解耦全流程解析
python·sqlite·信号与槽·pyqt5·数据库设计·桌面应用开发·事务处理
金銀銅鐵18 小时前
[Python] 体验用欧几里得算法计算最大公约数的过程
python·数学
FreakStudio21 小时前
W55MH32L-EVB 上手测评:硬件 TCP/IP 加持的以太网单片机,MicroPython 零门槛开发
python·单片机·嵌入式·大学生·面向对象·并行计算·电子diy·电子计算机
用户0332126663671 天前
使用 Python 从零创建 Word 文档
python
Csvn1 天前
Python 两大经典坑点 —— 可变默认参数 & 闭包延迟绑定
后端·python
曲幽1 天前
别再用网页翻译看源码了!你的私人翻译神器LibreTranslate,部署避坑指南来了
python·docker·web·pot·translate·libretranslate·arogstranslate
用户556918817531 天前
#从脚本到独立程序:Python + Playwright 批量抓取的完整踩坑记录
python·自动化运维