Python的字符编码
来源:互联网 发布:java函数返回值类型 编辑:程序博客网 时间:2024/06/06 02:38
http://www.cnblogs.com/BeginMan/p/3166363.html
一、字符编码中ASCII、Unicode和UTF-8的区别
点击阅读:http://www.cnblogs.com/kingstarspe/p/ASCII.html
再推荐一篇相关博文:http://www.cnblogs.com/huxi/archive/2010/12/05/1897271.html
二、Unicode与ASCII
Python能处理Unicode和ASCII编码,为了让这两者看起来尽可能的相似,Python字符串从原来简单的类型改成了真正的对象。ASCII字符串成了StringType、Unicode字符串成了UnicodeType。使用如下:
>>> "hello world" #ASCII string'hello world'>>> u"hello world" #Unicode stringu'hello world'>>>1、str()、chr()只能以0~255作为参数,也即是说只处理ASCII字符串。如果有Unicode字符串,则会先自动转换成ASCII的然后在传入这些函数中。
原因:Unicode支持的字符多,如果在str()、chr()中有ASCII不存在的字符,则会发生异常。
2、unicode()、unichar()可以看做是Unicode版本的str()和chr()。
>>> unicode('hello world')u'hello world'
三、编码与解码
它们解决的问题就是编码(encode())、解码(decode())问题,不至于出现乱码。
Codec表示编码方式。
""" 把一个Unicode字符串写入到磁盘文件,然后再把它读出并显示; 写入的时候用UTF-8,读也一样用UTF-8。""" CODEC = 'utf-8'FILE = 'demo.txt'strIn = u'BeginMan will be a great coder'byte_strIn = strIn.encode(CODEC) #以uft-8进行编码f = open(FILE,'w')f.write(byte_strIn)f.close()f = open(FILE,'r')str = f.read()f.close()str_out = str.decode(CODEC) #以utf-8进行解码print str_out #输出:BeginMan will be a great coder注意:
1、程序中出现字符串时一定要在前面加上前缀u
s= '博客园Cnblog' #不要这样写,这样容易乱码如:鍗氬鍥瑿nblogs = u'博客园Cnblog'#正确
2、不要使用str()函数,尽量用unicode()代替
3、不要使用过时的string 模块
4、没必要在程序中编码或解码unicode字符串,编码解码一般用于操作文件、数据库、网络等才使用。
5、字符串格式化
>>> '%s %s' %('Begin','man')'Begin man'#还记得上次的关于字符串的博客中说到的:“普通字符串与unicode字符串能转换成unicode字符串”>>> u'%s %s' %(u'Begin',u'Man')u'Begin Man'>>> u'%s %s' %('Begin','Man')u'Begin Man'>>> '%s %s' %(u'Begin','man')u'Begin man'>>> '%s %s' %('Begin',u'man')u'Begin man'
0 0
- Python的字符编码
- Python的字符编码问题
- python字符编码的判断
- Python字符编码的几个问题
- python的字符编码问题
- python 更改系统默认的字符编码
- 关于 python 字符编码的一些认识
- python字符编码错误的解决方案
- 彻底搞懂Python的字符编码
- python字符编码问题的总结
- Python检测文本字符编码的方法
- python入门(二):字符的编码
- 浅谈字符编码方式与python的中文编码(一)
- Python 中的字符编码
- Python字符编码详解
- Python 字符编码详解
- Python字符编码详解
- 关于python字符编码
- usaco training 4.4.3 Frame Up 题解
- 将list对象转换成json格式
- VS 2005使用map文件查找程序崩溃原因
- webService的使用
- LIBSVM入门解读
- Python的字符编码
- android Exception 研究
- 多个项目MyEclipse中启动OutOfMemoryError: PermGen space
- magento学习第一章
- 运算符优先级
- PAT (Advanced) 1032. Sharing (25)
- 视频软件TurboDemo 教程:如何为视频添加旁白和音乐
- Mac Terminal 菜鸟篇之目录跳转命令
- 如何配置LCD背光和LED,调试方法