zoukankan      html  css  js  c++  java
  • 编码和解码

    '''str是以字节表示的文本,unicode是以字符表示的文本。
    您可以将文本从字节解码为Unicode,并使用某种编码将Unicode编码为字节。
    即:'''
    #str - --------> str(Unicode) - --------> str
    # encode:编码,编程不可识别的unicode
    # decode:解码, 恢复成字符串和中文等
    def test1():
    
        u = '中文'  # 指定字符串类型对象u
        str1 = u.encode('gb2312')  # 以gb2312编码对u进行编码,获得bytes类型对象
        print(str1)  #str1:<class 'bytes'>
        #>>>b'xd6xd0xcexc4'
        str2 = u.encode('gbk')  # 以gbk编码对u进行编码,获得bytes类型对象
        print(str2)
        #>>>b'xd6xd0xcexc4'
        str3 = u.encode('utf-8')  # 以utf-8编码对u进行编码,获得bytes类型对象
        print(str3)
        #>>>b'xe4xb8xadxe6x96x87'
        u1 = str1.decode('gb2312')  # 以gb2312编码对字符串str进行解码,获得字符串类型对象
        print(u1)
        #>>>中文
        #u2 = str1.decode('utf-8')  # 报错,因为str1是gb2312编码的
        u3 = str3.decode('utf-8')   #str3是utf-8编的马,所以可以解
        print(u3)
        #>>>中文
        #print('ddd'.decode('utf-8')) #报错,已经是字符串了,还解什么码, 但是可以编码 如encode('utf-8')
        print(type(str1))
        #>>><class 'bytes'>
        print(type(u3))
        #>>><class 'str'>
    
    if __name__=='__main__':
        test1()
    

      

    读取文件,发现数据文件的编码是gb2312,所以读取一行内容后需要转为unicode然后再转为utf8:

    line = line.decode('gbk').encode('utf-8')

    (奇怪的是用’gb2312’就不行)

    unicode是中转站



  • 相关阅读:
    HDU-4248 A Famous Stone Collector 组合数学 DP
    HDU
    暑期训练1 Gym
    暑期训练1 Gym-102623L Lottery Tickets 模拟 贪心构造
    暑期训练2 Gym
    poj-1011 sticks(搜索题)
    hdu-2553 N皇后问题(搜索题)
    poj-2236 wireless network(并查集)
    poj-1700 crossing river(贪心题)
    poj-3278 catch that cow(搜索题)
  • 原文地址:https://www.cnblogs.com/lxgbky/p/12427092.html
Copyright © 2011-2022 走看看