python有strobject和unicodeobject兩種字符串,都可以存放字符的字節編碼,但是他們是不同的type,這一點很重要,也是為什么會有encode和decode。
encode和decode在pyhton中的意義可表示為
encode將
unicode----->str
decode
unicode<-------str
幾種常用法:
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文件中指定,比如
importsys
sys.setdefaultencoding('utf-8')
以上內容為大家介紹了python培訓之怎么處理Python字符編碼轉換?,希望對大家有所幫助,如果想要了解更多Python相關知識,請關注IT培訓機構:千鋒教育。