python 默认编码的理解与设置

发布时间:2019-08-27 07:59:12编辑:auto阅读(1649)

     原链接:

    http://notewo.sinaapp.com/blog/full_article/?blogid=54

     

    python 里面的编码和解码,就是unicode  和str 这两种形式的相对转换。
    编码: unicode  → str
    解码: str        → unicode

    有两个设置编码的知识点
    1、文件开头的:# -*-  coding=utf8  -*-
            python的默认脚本文件都是以utf8编码的,当文件中有非utf8编码范围内的字符的时候就要使用“编码提示”来修正。

    2、sys.setdefaultencoding('utf-8')
    先说下如何使用:

    >>> import sys
    >>> reload(sys)

    <module 'sys' (built-in)>

    >>> sys.setdefaultencoding('utf8')

    >>>

      reload(sys) 这一句是必须的,当脚本加载完毕之后,会把setdefaultencoding这个方法给删掉,我们需要reload(sys) 才可以使用。
    用实例来理解它的作用:

    >>> import sys

    >>> sys.getdefaultencoding()

    'ascii'

    >>> str = "中文"

    >>> print str

    中文

    >>> str.encode('utf8')

    Traceback (most recent call last):

     File "<stdin>", line 1, in <module>

    UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)

    无法将str编码为utf8。

    编码: unicode  → str
    解码: str        → unicode


    >>> str.encode('utf8') 这一句在执行的时候,会先将str解码为ascii(也就是sys.setdefaultcoding()所设置的值,默认是ascii),再编码为utf8。

    ascii并不是unicode的编码形式之一。所以无法进行这种类型的转换。

    转换过程如下:
    str  --------> unicode --------------> str(utf8)
                            |
                            |
                  unicode这里就是指setdefaultcoding()所设的值。


    再进行实验:

    >>> import sys

    >>> reload(sys)

    <module 'sys' (built-in)>

    >>> sys.setdefaultencoding('utf8')

    >>> str.encode('utf8')

    '\xe4\xb8\xad\xe6\x96\x87'

    >>> print str

    中文

    >>>


    这样子就可以了,转换流程变为如下:
    str ---------> unicode(utf8) -----------> str(utf8)

关键字