Python中bytes和str的区别与联系详解

咖啡半糖
咖啡半糖
发布时间:2026-10-15| 4人浏览过
原创

本文详解Python 3中bytes与str的核心区别,前者为8位无符号序列,后者为Unicode字符。通过encode和decode方法实现互转,并强调文件读写时mode参数(wb/rb)与encoding设置的重要性,避免类型错误与乱码。

Bytes和Str的区别

在Python 3版本中,字符序列主要包含两种类型:bytes和str。其中,bytes类型由无符号的8位值组成,通常以ASCII码形式展示;而str类型则基于Unicode代码点(code point)。所谓代码点,指的是在编码字符集中,每个字符所对应的具体数字编号。

a = b'hello world'
print(isinstance(a, bytes))
print(list(a))
print(a)
"""
True
[104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
b'hello world'
"""

a = 'hello world'
print(isinstance(a, str))
print(list(a))
print(a)
"""
True
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
hello world
"""

可以使用isinstance()函数来检测对象的具体类型,例如通过该函数判断变量属于str还是bytes类型。

Python 3对文本数据(str)和二进制数据(bytes)实施了严格的类型隔离,两者不可直接混用。

x = b'python'
y = b'java'
z = 'c++'
w = 'c'

print(x + y)
# b'pythonjava'
print(z + w)
# c++c
print(x + z)
# TypeError: can't concat str to bytes

print('python' == b'python')
# False

在前述示例中,若使用等号(=)直接比较str类型与bytes类型是否相等,程序不会抛出错误,但运算结果始终为False。

Bytes与Str间的转换

str类型与bytes类型之间支持相互转换。

将str转换为bytes时,需要调用encode()方法。

将bytes转换为str时,需要调用decode()方法。

x = b'python'
y = x.decode(encoding='utf-8')
z = y.encode(encoding='utf-8')
print(y)
print(z)
"""
python
b'python'
"""

可以注意到,encode()和decode()方法均包含一个encoding参数,用于指定具体的编码规则。

读写文件的注意事项

当需要将bytes类型数据写入文件时,必须指定mode参数为'wb'。在读取二进制文件时,可以指定mode为'rb',或者指定编码方式;若采用后者,读取到的结果将不再是bytes类型的字符序列。

x = b'python'

# 错误示例
with open('data.bin', mode='w') as fp:
    fp.write(x)
# TypeError: write() argument must be str, not bytes

# 正确示例
with open('data.bin', mode='wb') as fp:
    fp.write(x)

# 读取二进制文件方式1
with open('data.bin', mode='rb') as fp:
    content = fp.read()
    print(content)
# python

# 读取二进制文件方式2
with open('data.bin', mode='r', encoding='utf-8') as fp:
    content = fp.read()
    print(content, type(content))
# python <class 'str'>

当进行Unicode数据的读写操作时,只需关注编码方式,建议显式传递encoding参数以确保兼容性。

x = '世界你好'

with open('data.txt', mode='w', encoding='utf-8') as fp:
    fp.write(x)

with open('data.txt', mode='r', encoding='utf-8') as fp:
    content = fp.read()
    print(content)
# 世界你好

# 错误示例,编码方式不对
with open('data.txt', mode='r', encoding='gbk') as fp:
    content = fp.read()
    print(content)
# 涓栫晫浣犲ソ

总结

至此,关于Python中bytes和str区别与联系的讲解完毕。如需了解更多Python bytes和str相关内容,请搜索本站历史文章或继续浏览后续文章,感谢大家的支持!

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。