Python中的编码和解码问题

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

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

>>>a='你好'
>>>ae=a.encode('utf-8')
>>>ae
b'xe4xbdxa0xe5xa5xbd'
>>>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:softsAnacondalibsite-packagesIPythoncoreinteractiveshell.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()函数

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

>>>s1='u534eu4e3au624bu673auff0cu597du7528u4e0du8d35uff0cu5988u5988u518du4e5fu4e0du7528u62c5u5fc3u6211u53d8u6210u6708u5149u65cfu4e86~'
>>>s1.encode('utf-8').decode('utf-8')
'华为手机,好用不贵,妈妈再也不用担心我变成月光族了~'
>>>type(s1)
 str

  

原文地址:https://www.cnblogs.com/zz22--/p/9556755.html