当前位置: 首页 > 图文教程 > 脚本技术 > Python > python 中文字符串的处理实现代码

Python
Python入门教程 超详细1小时学会Python
复制粘贴功能的Python程序
python远程登录代码
Python Mysql自动备份脚本
py中的目录与文件判别代码
python下如何让web元素的生成更简单的分析
Python 文件操作技巧(File operation) 实例代码分析
python备份文件的脚本
Python备份Mysql脚本
rhythmbox中文名乱码问题解决方法
Python交换变量
Python字符遍历的艺术
Python字符转换
Python isinstance判断对象类型
Python ljust rjust center输出
Python strip lstrip rstrip使用方法
Python 连接字符串(join %)
Python 字符串中的字符倒转
Python translator使用实例
Python 除法小技巧

Python 中的 python 中文字符串的处理实现代码


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2010-01-10   浏览: 261 ::
收藏到网摘: n/a

python中直接将一个中文字符串赋值给一个变量使用的是utf-8格式的编码,以下为证. >>> teststr = '我的eclipse不能正确的解码gbk码!'
>>> teststr
'\xe6\x88\x91\xe7\x9a\x84eclipse\xe4\xb8\x8d\xe8\x83\xbd\xe6\xad\xa3\xe7\xa1\xae\xe7\x9a\x84\xe8\xa7\xa3\xe7\xa0\x81gbk\xe7\xa0\x81\xef\xbc\x81'
>>> tests2 = u'我的eclipse不能正确的解码gbk码!'
>>> test3 = tests2.encode('gb2312')
>>> test3
'\xce\xd2\xb5\xc4eclipse\xb2\xbb\xc4\xdc\xd5\xfd\xc8\xb7\xb5\xc4\xbd\xe2\xc2\xebgbk\xc2\xeb\xa3\xa1'
>>> test3
'\xce\xd2\xb5\xc4eclipse\xb2\xbb\xc4\xdc\xd5\xfd\xc8\xb7\xb5\xc4\xbd\xe2\xc2\xebgbk\xc2\xeb\xa3\xa1'
>>> teststr
'\xe6\x88\x91\xe7\x9a\x84eclipse\xe4\xb8\x8d\xe8\x83\xbd\xe6\xad\xa3\xe7\xa1\xae\xe7\x9a\x84\xe8\xa7\xa3\xe7\xa0\x81gbk\xe7\xa0\x81\xef\xbc\x81'
>>> test3.decode('gb2312').encode('utf-8')
'\xe6\x88\x91\xe7\x9a\x84eclipse\xe4\xb8\x8d\xe8\x83\xbd\xe6\xad\xa3\xe7\xa1\xae\xe7\x9a\x84\xe8\xa7\xa3\xe7\xa0\x81gbk\xe7\xa0\x81\xef\xbc\x81'
>>> test3.decode('gb2312').encode('utf-8') == teststr
True
如上所见,test3变量(gb2312编码)经过解码(变成unicode字符串)后再使用utf-8编码,就成了与teststr值相同的串了.
通过上面的例子我们也发现,unicode字符串是gb2312字符串(windows就使用这种格式)与utf-8字符串(python本身使用)之间的一座桥梁.