Python系列(五):bytes和str的区别与联系

Bytes和Str的区别

在Python3中,字符序列有两种类型:bytesstrbytes类型是无符号的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

Python3对文本(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类型间可以相互转换。
strbytes的转换需要调用encode()方法。
bytesstr间的转换需要调用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)
# 涓栫晫浣犲ソ
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

斯曦巍峨

码文不易,有条件的可以支持一下

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值