Python中bytes和str的区别与联系详解
本文详解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相关内容,请搜索本站历史文章或继续浏览后续文章,感谢大家的支持!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













