ITPub博客

首页 > IT职业 > IT生活 > 怎么处理Python字符编码转换?

怎么处理Python字符编码转换?

IT生活 作者:sprest 时间:2021-09-11 10:35:29 0 删除 编辑

python 有str object 和 unicode object 两种字符串, 都可以存放字符的字节编码,但是他们是不同的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
'xb3xa4xb3xc7'
>>> t.decode('gb2312').encode('utf-8')
'xe9x95xbfxe5x9fx8e'

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')

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3088/viewspace-2837022/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-13

  • 博文量
    101
  • 访问量
    821