美文网首页
python2编码

python2编码

作者: cotecc | 来源:发表于2018-03-16 13:59 被阅读0次

    一、概念

    python2默认ascii码,可以在文件头显式指定编码(utf-8,此时所有str的编码都是utf-8)
    python2底层两种编码:

    • str,二进制编码
    • unicode,与存储无关的编码
    #coding:gb2312
    ss="你好"                #使用gb2312编码的str
    print type(ss) 
    ss=ss.decode('gb2312')   #解码成unicode
    print type(ss)
    
    #coding:utf-8
    ss="你好"                #使用utf8编码的str
    print type(ss)
    ss=ss.decode("utf8")     #解码成unicode
    print type(ss)
    
    #coding:utf-8
    ss=u"你好"               #unicode
    print type(ss)
    ss=ss.encode("utf-8")    #编码成unicode
    print type(ss)
    

    二、chardet查看编码
    chardet接受二进制编码输入,输出对应的编码类型

    #coding:utf-8
    import chardet
    
    ss="你好"                                      #utf-8
    str_type = chardet.detect(ss)  
    print str_type['encoding']              #utf-8
    
    

    相关文章

      网友评论

          本文标题:python2编码

          本文链接:https://www.haomeiwen.com/subject/renlqftx.html