總的來說,bytes和string的關系是:
\(bytes\xrightarrow{decode}string\)
\(bytes\xleftarrow{encode}string\)
常見的幾種編碼及格式
- utf8:形如\xe4\xbb\x8a\xe5\xa4
- unicode:形如\u4eca\u5929\u5929\u6c14\u4e0d\u9519
- 注意:如果\變成了\\說明,原字符串是編碼后的格式,變成\\是因為轉換成了bytes
下面是幾種常見的功能
- string轉bytes
s = "abc" #string
s = "abc".encode() #bytes,encode默認編碼方式是utf-8
s = b"abc" #bytes
- bytes轉string
s = b"abc" #bytes
s = b"abc".decode() #string,encode默認編碼方式是utf-8
s = str(b"") #string
- bytes類型的unicode(中文)輸出
s = '\\u4eca\\u5929\\u5929\\u6c14\\u4e0d\\u9519' #中文是:今天天氣真不錯
new_s = s.encode().decode('unicode_escape') #輸出為:今天天氣真不錯