zoukankan      html  css  js  c++  java
  • Python3中如何解决中文乱码与编码的问题

    1.解决乱码问题:   

        pyhton中内部所有编码是Unicode,中文是gbk;正常情况下,我们输出的是utf-8;  

        我们可以采用sys.getdefaultencoding()查看系统默认的编码; 解决方法有如下几种:

            1.在文件开头添加上:#coding:utf-8或者# -*- coding:utf-8 -*-

             2.转换路径:原文件编码 ->unicode中转码 ->我们需要的编码格式     (decode()可选) ->unicode ->encode(),如果内容已经unicode,则不需要decode(),直接使用encode()

             3.举例:  

                     a.如果网页是utf-8,我们可使用html.read().decode('utf-8')将网页在控制台打印;  

                     b.如果网页是gb2312,则使用html.read().decode('gbk').encode(''utf-8)正常打印;(注意:decode('gbk')不能使用gbk2312,需用统一使用gbk)  

             4.判断指定的内容是什么编码:(注意:使用unicode只针对python2,python3已经取消了unicode函数,python3默认是utf8编码,Python 3中基本的str就是unicode,所以可以直接判断str: >>> isinstance('s', str) True)      

                   if isinstance(content,unicode):表示如果content编码为unicode则为True,否则False

  • 相关阅读:
    Autofac 依赖注入
    C#高级语法
    @helper
    Spiral Matrix -- LeetCode
    Best Time to Buy and Sell Stock with Cooldown -- LeetCode
    Kth Smallest Element in a Sorted Matrix -- LeetCode
    Number of Connected Components in an Undirected Graph -- LeetCode
    Super Ugly Number -- LeetCode
    Ugly Number II -- LeetCode
    Missing Ranges -- LeetCode
  • 原文地址:https://www.cnblogs.com/ysq0908/p/9420436.html
Copyright © 2011-2022 走看看