python转码要诀

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之间的转换
好比:
python

>>> 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文件中指定,好比
spa

import sys
sys.setdefaultencoding(
'utf-8')code

相关文章
相关标签/搜索