Python 字元編碼轉換秘訣

來源:互聯網
上載者:User
python 有str object 和 unicode object 兩種字串, 都可以存放字元的位元組編碼,但是他們是不同的type,這一點很重要,也是為什麼會有encode 和decode。

encode 和 decode在pyhton 中的意義可表示為

encode

unicode -------------------------> str

unicode <--------------------------str

decode

幾種常用法:

str_string.decode('codec') 是把str_string轉換為unicode_string, codec是源str_string的編碼方式

unicode_string.encode('codec') 是把unicode_string 轉換為str_string,codec是目標str_string的編碼方式

str_string.decode('from_codec').encode('to_codec') 可實現不同編碼的str_string之間的轉換

比如:

>>> t='長城'

>>> t

'\xb3\xa4\xb3\xc7'

>>> t.decode('gb2312').encode('utf-8')

'\xe9\x95\xbf\xe5\x9f\x8e'

str_string.encode('codec') 是先調用系統的預設codec去把str_string轉換為unicode_string,然後用encode的參數codec去轉換為最終的str_string. 相當於str_string.decode('sys_codec').encode('codec')。

unicode_string.decode('codec') 基本沒有意義,unicode 在python裡只用一種unicode編碼,UTF16或者UTF32(編譯python時就已經確定),沒有編碼轉換的需要。

註:預設codec在site-packages下的sitecustomize.py檔案中指定,比如

import sys

sys.setdefaultencoding('utf-8')

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.