专栏名称: Python开发者
人生苦短,我用 Python。伯乐在线旗下账号「Python开发者」分享 Python 相关的技术文章、工具资源、精选课程、热点资讯等。
目录
相关文章推荐
Python爱好者社区  ·  月薪3万35岁脑干出血程序员:ICU躺了28 ... ·  2 天前  
Python爱好者社区  ·  务必立即拿下软考证(政策红利) ·  3 天前  
Python爱好者社区  ·  软考,yyds ·  2 天前  
Python爱好者社区  ·  Science披露:近3年,垃圾论文激增,9 ... ·  3 天前  
51好读  ›  专栏  ›  Python开发者

Python: 熟悉又陌生的字符编码

Python开发者  · 公众号  · Python  · 2017-02-23 21:38

正文

请到「今天看啥」查看全文


for more information .

>>> import sys

>>> sys . getdefaultencoding ()

'ascii'


  • Python3


Python 3.5.2 ( default , Jun 29 2016 , 13 : 43 : 58 )

[ GCC 4.2.1 Compatible Apple LLVM 7.3.0 ( clang - 703.0.31 )] on darwin

Type "help" , "copyright" , "credits" or "license" for more information .

>>> import sys

>>> sys . getdefaultencoding ()

'utf-8'


Python2 中的字符类型


Python2 中有两种和字符串相关的类型:str 和 unicode,它们的父类是 basestring。其中,str 类型的字符串有多种编码方式,默认是 ascii,还有 gbk,utf-8 等,unicode 类型的字符串使用 u'...' 的形式来表示,下面的图展示了 str 和 unicode 之间的关系:



两种字符串的相互转换概括如下:


  • 把 UTF-8 编码表示的字符串 ‘xxx’ 转换为 Unicode 字符串 u’xxx’ 用 decode('utf-8') 方法:


>>> '中文' . decode ( 'utf-8' )

u '\u4e2d\u6587'


  • 把 u’xxx’ 转换为 UTF-8 编码的 ‘xxx’ 用 encode('utf-8') 方法:


>>> u '中文' . encode ( 'utf-8' )

'\xe4\xb8\xad\xe6\x96\x87'


UnicodeEncodeError & UnicodeDecodeError 根源


用 Python2 编写程序的时候经常会遇到 UnicodeEncodeError 和 UnicodeDecodeError,它们出现的根源就是 如果代码里面混合使用了 str 类型和 unicode 类型的字符串,Python 会默认使用 ascii 编码尝试对 unicode 类型的字符串编码 (encode),或对 str 类型的字符串解码 (decode),这时就很可能出现上述错误。


下面有两个常见的场景,我们最好牢牢记住:


  • 在进行同时包含 str 类型和 unicode 类型的字符串操作时,Python2 一律都把 str 解码(decode)成 unicode 再运算,这时就很容易出现 UnicodeDecodeError。







请到「今天看啥」查看全文