Python中的编码和解码问题

关于Python中遇到的中文字符串的读取和输入时总是遇到一堆问题,到现在还不是特别明白,只是有了一个大概率的理解,就是:字符串是用什么编码格式编码的,就用什么编码格式来解码。

encode()对字符串st进行编码,按照制定的编码格式编码。编码后为字节流,bytes。编码是从中间编码格式Unicode来向其他编码格式来映射的,而Unicode的表示就是字符串str。可以直接对字符串编码。

>>>a='你好'
>>>ae=a.encode('utf-8')
>>>ae
b'\xe4\xbd\xa0\xe5\xa5\xbd'
>>>type(ae)
bytes

decode()对编码后的字节流进行解码,按照编码的格式进行解码,解码为中间格式Unicode,并且由str类型进行表示。比如上面的例子,下面解码必须要以编码相同的格式解码‘utf-8’,否则会报错。

>>>au=ae.decode('utf-8')
>>>au
'你好'
>>>ae.decode('gbk')
 '浣犲ソ'

如果用str的字符串来解码会出现错误,因为str字符串表示的是Unicode,Python本身默认的编码格式就是Unicode,所以str可以编码

>>>a.decode('utf-8')
Traceback (most recent call last):
  File "G:\softs\Anaconda\lib\site-packages\IPython\core\interactiveshell.py", line 2963, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-68-fe89aebaa52b>", line 1, in <module>
    a.decode('utf-8')
AttributeError: 'str' object has no attribute 'decode'

下面推荐介个看的链接:

1.python3大作战之encode与decode讲解

2.python中的encode()和decode()函数

 

当遇到显示为'\u534e\u4e3a\u624b\u673a\uff0c\u597d'的字符串时,表明这个字符串已经是Unicode编码的格式了,所以可以直接先编码为一个格式,再解码,就可以看到能看得懂的中文字符串了

>>>s1='\u534e\u4e3a\u624b\u673a\uff0c\u597d\u7528\u4e0d\u8d35\uff0c\u5988\u5988\u518d\u4e5f\u4e0d\u7528\u62c5\u5fc3\u6211\u53d8\u6210\u6708\u5149\u65cf\u4e86~'
>>>s1.encode('utf-8').decode('utf-8')
'华为手机,好用不贵,妈妈再也不用担心我变成月光族了~'
>>>type(s1)
 str

  

posted @ 2018-08-29 20:51  樟樟22  阅读(2848)  评论(0编辑  收藏  举报