python3 的 str与bytes

string and bytes

  python3只有一种保存文本信息的数据类型:str,str是一种不可变序列,保存的数据是Unicode的“码位”信息,说白了就是某个(utf-8,big-5等)编码集中的字符。
python3的bytes或者bytearray与str不同,只能存储‘十六进制的0 - 255’(也就是8位(2^8))以内的编码组成的不可修改的数组,编码的含义由不同的编码方式(utf-8, big5等)决定。
  白话文:string存储的是字符列表,bytes存储的是字符的编码的数组。
string 和 bytes之间的转换
  string和bytes之间的转换:
string_and_bytes

>>> b = bytes('中文', 'utf-8')
>>> b
b'\xe4\xb8\xad\xe6\x96\x87'
>>> b.decode('Windows 1252')
'ä¸\xadæ–‡'
>>> b.decode('ISO8859-7')
'δΈ\xadζ\x96\x87'
>>> string = b.decode('utf-8')
>>> string
'中文'
>>> b = string.encode('utf-8')
>>> b
b'\xe4\xb8\xad\xe6\x96\x87'
>>> 

猜你喜欢

转载自blog.csdn.net/steventian72/article/details/85716700
今日推荐