打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
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之间的转换
比如:

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

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Python 编码为什么那么蛋疼?
Python的中文编码问题
黄聪:解决python中文处理乱码,先要弄懂“字符”和“字节”的差别
扶凯 ? Perl Unicode全攻略(转)
decode和encode
bytes类型--python
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服