当前位置:编程学习 > 网站相关 >>

python之中文字符串的处理方法介绍

python中直接将一个中文字符串赋值给一个变量使用的是utf-8格式的编码,以下为证.
>>> teststr = 我的eclipse不能正确的解码gbk码!
>>> teststr
xe6x88x91xe7x9ax84eclipsexe4xb8x8dxe8x83xbdxe6xadxa3xe7xa1xaexe7x9ax84xe8xa7xa3xe7xa0x81gbkxe7xa0x81xefxbcx81
>>> tests2 = u我的eclipse不能正确的解码gbk码!
>>> test3 = tests2.encode(gb2312)
>>> test3
xcexd2xb5xc4eclipsexb2xbbxc4xdcxd5xfdxc8xb7xb5xc4xbdxe2xc2xebgbkxc2xebxa3xa1
>>> test3
xcexd2xb5xc4eclipsexb2xbbxc4xdcxd5xfdxc8xb7xb5xc4xbdxe2xc2xebgbkxc2xebxa3xa1
>>> teststr
xe6x88x91xe7x9ax84eclipsexe4xb8x8dxe8x83xbdxe6xadxa3xe7xa1xaexe7x9ax84xe8xa7xa3xe7xa0x81gbkxe7xa0x81xefxbcx81
>>> test3.decode(gb2312).encode(utf-8)
xe6x88x91xe7x9ax84eclipsexe4xb8x8dxe8x83xbdxe6xadxa3xe7xa1xaexe7x9ax84xe8xa7xa3xe7xa0x81gbkxe7xa0x81xefxbcx81
>>> test3.decode(gb2312).encode(utf-8) == teststr
True
如上所见,test3变量(gb2312编码)经过解码(变成unicode字符串)后再使用utf-8编码,就成了与teststr值相同的串了.

通过上面的例子我们也发现,unicode字符串是gb2312字符串(windows就使用这种格式)与utf-8字符串(python本身使用)之间的一座桥梁.
补充:Web开发 , Python ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,