Python - 編碼轉換

  1. # coding: utf-8


    s = 'abc'
    print type(s) # str(utf-8)
    print len(s) # 3


    s = unicode(s) # str -> unicode,其中str的每個字符值必須小於128
    print type(s) # unicode
    print len(s) # 3


    s = u'abc'
    print type(s) # unicode
    print len(s) # 3


    s = s.encode('utf-8') # unicode -> str(utf-8)
    print type(s) # str
    print len(s) # 3


    s = s.decode('utf-8') # str(utf-8) -> unicode,這裏str的每個字符值任意
    print type(s) # unicode
    print len(s) # 3


    s = '中國' # 由於整個文件以utf-8編碼
    print type(s) # str(utf-8)
    print len(s) # 6


    s = u'中國'
    print type(s) # unicode
    print len(s) # 2


    s = s.encode('utf-8')
    print type(s) # str(utf-8)
    print len(s) # 6


    s = s.decode('utf-8')
    print type(s) # unicode
    print len(s) # 2


    s = raw_input(u'輸入:') # windows下貌似中文按gbk編碼,每個中文佔2個字節
    print type(s) # str(gbk)
    print len(s) # 4


    s = s.decode('gbk') # 要想gbk編碼轉爲utf-8編碼,先將gbk編碼轉爲unicode
    print type(s) # unicode
    print len(s) # 2


    s = s.encode('gbk')
    print type(s) # str(gbk)
    print len(s) # 4


    # 根據以上的驗證,得出結論
    # 各種編碼都可以通過unicode來轉化,unicode可以假想爲一張各種字符的對照表,在這個表中可以找到世界範圍內的任何一種字符
    # 當然,也包括中文,每個字符都對應一個序號,如'a' -> 0x61,'中' -> 0x4e2d
    # unicode -> utf-8 unicode.encode('utf-8')
    # utf-8 -> unicode str.decode('utf-8')
    # gbk -> unicode str.decode('gbk')
    # unicode -> gbk unicode.encode('gbk')
發佈了16 篇原創文章 · 獲贊 9 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章