python3中的str和bytes

Python2的字符串有两种:str 和 unicode;Python3的字符串也有两种:str 和 bytes。

bytes可以是任何二进制数据,文本/图片/视频/音频等等。

str就是文本。


str与bytes互转

b = b"example"    # bytes object  
s = "example"     # str object  

s2b = bytes(s, encoding = "utf8")    # str to bytes 
s2b = str.encode(s)             # str to bytes 
s2b = s.encode("utf8")             # str to bytes 

b2s = str(b, encoding = "utf8")      # bytes to str  
b2s = bytes.decode(b)           #  bytes to str  
b2s = b.decode("utf8")           #  bytes to str  

略微详细的介绍

Python3 严格区分文本数据(str)和二进制数据(bytes)。文本数据可以变成二进制数据,但是二进制数据不一定是文本数据。比如图片,视频也可以用二进制数据(bytes)表示。

所以python3中bytes和str不能混用。因为bytes不一定能变成str,不同类型之间操作就会抛出TypeError的异常。

str和bytes的转换关系(注意bytes不一定能decode成str哦)

str.encode('encoding') -> bytes

bytes.decode('encoding') -> str

# encoding可以是 utf-8, gb2312, gbk等等

当bytes是图片,视频等非文本的二进制内容时,bytes就不能decode成str了。

In [29]: img = open('str-bytes.jpg', 'rb').read()

In [30]: type(img)
Out[30]: bytes

In [31]: img.decode('utf8')
---------------------------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
<ipython-input-31-c9e28f45be95> in <module>()
----> 1 img.decode('utf8')

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
posted @ 2020-03-29 16:22  ZH奶酪  阅读(2728)  评论(0编辑  收藏  举报