在python中,字符串在内存中都是以字节的形式呈现
在python中,字节都是以整数(0~255)的形式显现
在python中,字节流默认是以utf-8的格式进行编码和解码
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> mystr='linux中国'
>>> mystr
'linux中国'
把mystr字符串编码为GBK字节流
>>> gbk=bytes(mystr,encoding='GBK')
>>> gbk
b'linux\xd6\xd0\xb9\xfa'
把这个字节流用utf-8的格式进行解码,当然是失败的
>>> gbk.decode(encoding='utf-8')#调用decode对gbk进行解码
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
gbk.decode(encoding='utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd6 in position 5: invalid continuation byte
把这个字节流用utf-8的格式进行解码,当然是失败的
>>> str(gbk,encoding='utf-8')#使用str函数对gbk字节流解码
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
str(gbk,encoding='utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd6 in position 5: invalid continuation byte
用GBK格式编码,就要用GBK解码
>>> gbk.decode(encoding='GBK')
'linux中国'
>>> str(gbk,encoding='GBK')
'linux中国'
>>>