zoukankan      html  css  js  c++  java
  • Python中 sys.setdefaultencoding("utf8") 的作用详解

    在处理中文数据,经常加入下面的代码:

    import sys
    reload(sys)
    sys.setdefaultencoding("utf8")

    设置python默认字节流编/解码器按照utf8解码方式,把字节流编/解码为unicode;

    具体来说,所起到的作用,可以用下面两个错误来解释:

    1. 在将字节流使用str()方法转换为str对象时,会调用默认的encode函数,如果没有上述系统的默认编码设置,则自动使用'ascii' codecs进行编码,对于非ascii编码的数据,比如utf8字节流会产生错误解码提示:

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

            2.在utf8编码文件中写入汉字字符, 比如 s = '中文'时, 如果没有上述设置,运行程序会在初始s对象的值,报告错误解码提示:

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

  • 相关阅读:
    windows nginx
    stdClass 标准
    array_merge
    array_pop
    array_push
    array_unique
    GMT与UTC简介(转)
    curl-手册
    13.5. zipfile — Work with ZIP archives
    7. Input and Output
  • 原文地址:https://www.cnblogs.com/operaculus/p/11827889.html
Copyright © 2011-2022 走看看