Python字符串编码的encode与decode

一.编码转换

通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。


1.decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串转换成unicode编码。

2.encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串转换成gb2312编码。

3.encode的时候注意这个编码,可以解决unicode中文转换的问题

Codec Operand type Purpose
raw_unicode_escape Unicode string Produce a string that is suitable as raw Unicode literal in Python source code

如:froms=froms.encode('raw_unicode_escape', 'ignore').decode('GB18030', 'ignore')



注意:输出的时候需要考虑IDE的环境变量,可能会出现乱码,甚至可能会提示:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)。



二.Python代码中的编码定义

1.代码中字符串的默认编码与代码文件本身的编码一致,如:

s='中文'

如果是在utf8的文件中,该字符串就是utf8编码

如果是在gb2312的文件中,则其编码为gb2312。

这种情况下,要进行编码转换,都需要先用decode方法将其转换成unicode编码,再使用encode方法将其转换成其他编码。


通常,在没有指定特定的编码方式时,都是使用的系统默认编码创建的代码文件

$ python -c "import sys; print sys.getdefaultencoding()"

ascii



2.如果字符串是这样定义:

s=u'中文'

则该字符串的编码就被指定为unicode了,即python的内部编码,而与代码文件本身的编码无关。

因此,对于这种情况做编码转换,只需要直接使用encode方法将其转换成指定编码即可。



你可能感兴趣的:(decode,encode,python编码)