zoukankan      html  css  js  c++  java
  • py2与py3防止中文乱码设置头部

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    
    
    """
    https://blog.csdn.net/weixin_34195364/article/details/88988634
    
    python在安装时,默认的编码是ascii,当程序中出现非ascii编码时,
    python的处理常常会报错UnicodeDecodeError: 'ascii' codec can't decode byte 0x?? in position 1: ordinal not in range(128),
    python没办法处理非ascii编码的,此时需要自己设置python的默认编码,一般设置为utf8的编码格式。
    
    在程序中加入以下代码:即可将编码设置为utf8
    -- py2
    import sys
    reload(sys)
    sys.setdefaultencoding('utf8')
    
    import sys
    reload(sys)
    sys.setdefaultencoding(‘utf-8’)
    以上是python2的写法,但是在python3中这个需要已经不存在了,这么做也不会什么实际意义。
    在Python2.x中由于str和byte之间没有明显区别,经常要依赖于defaultencoding来做转换。
    在python3中有了明确的str和byte类型区别,从一种类型转换成另一种类型要显式指定encoding。
    
    但是仍然可以使用这个方法代替
    import importlib,sys
    importlib.reload(sys)
    """
    import os
    import sys
    import imp
    
    # 防止出现中文乱码,程序重启重新加载模块
    PY_VERSION = sys.version_info
    PY_V_INFO = str(PY_VERSION.major) + "." + str(PY_VERSION.minor) + "." + str(PY_VERSION.micro)
    
    if PY_VERSION < (3, 0):
        print('当前python版本号为:%s', PY_V_INFO)
        reload(sys)
        sys.setdefaultencoding('utf-8')
    else:
        import importlib
    
        importlib.reload(sys)
    
    人生苦短,我用python!
  • 相关阅读:
    Relax! It's just a game(排列组合,简单)
    Feynman(数学)
    The Center of Gravity(一道很很简单的几何题)
    Game with points(数学,难度中)
    Tempter of the Bone(DFS + 奇偶剪枝,好题)
    [置顶] Card
    Find Terrorists(素数筛选+素因子分解)
    Enemy at the Gateway
    Anindilyakwa(简单)
    ACMer(数学,有意思)
  • 原文地址:https://www.cnblogs.com/sunxiuwen/p/14790570.html
Copyright © 2011-2022 走看看