Python字符串的encode与decode

Python使用过程中会出现各式各样的乱码问题,明明是中文字符却显示成“/xe4/xb8/xad/xe6/x96/x87”的形式.

字符串在Python内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码,

即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。

如:

  str = str.decode('utf-8') 表示将utf-8编码的字符串str转换成unicode编码。

  str = str.encode('gbk2312') 表示将unicode编码的str转换成gbk2312编码。

因此,转码的时候一定要先搞明白,字符串str是什么编码,然后decode成unicode,然后再encode成其他编码

原文地址:https://www.cnblogs.com/SZxiaochun/p/6961317.html