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() 键值对序列 字典 结构化数据
相关推荐
在世修行3 小时前
智学文枢:页面切换与跨页数据预填
python·桌面应用·signal·1024程序员节·pyside·跨页跳转·状态预填
2601_962885723 小时前
如何用 Python 把 K 线重采样成任意周期?
开发语言·python
打工仔折腾 AI3 小时前
在 Ubuntu ARM64 部署 Q1 V3.0 MuJoCo 模型:加载、单步推理与执行器响应解析
linux·运维·人工智能·python·深度学习·ubuntu·性能优化
信誓旦旦的程序猿4 小时前
【Python量化实战宝典 #21】北向资金跟随手册:聪明钱择时信号(Python 可跑)
python·1024程序员节·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口
严谨的麻辣烫4 小时前
静态 ISP 代理请求超时怎么排查?Python 与 curl 实战
python·http·requests·1024程序员节·网络排障
KeepRobots6 小时前
11-01 温哥华不回拨:用 60 行 Python 查你的工单系统会不会差一小时(KeepRobots 工程笔记)
python
xiao77mwq6 小时前
你以为 OCR 慢?实测 81.3 s 里全是故障代价:如何把「定格态」消掉,让耗时从 6.5 s 到 13 倍差距显出原形
python
深圳市益普科技有限公司6 小时前
半导体良率管理YMS:良率与设备参数的相关性,先拉哪几组数据
人工智能·python·算法
“AI国潮设计-小江”6 小时前
【AIGC实战】Python+SDXL打造“潮汕英歌舞IP”万能立牌插件,批量生成“发财元宝蛋糕”视觉营销方案(附源码)
开发语言·人工智能·python·prompt·aigc
砚底藏山河7 小时前
python量化实操:冷热分层存储
java·开发语言·python·金融