首页 > 编程语言 > 详细

python2和python3中字符编码区别

时间:2019-11-11 16:38:55      阅读:99      评论:0      收藏:0      [点我收藏+]

在python2和python3中,字符在内存中以unicode形式存在。在进行编码方式转换时,unicode形式应作为中介,在decode和encode中转换。如下图:

技术分享图片

 

python2中的字符编码

在ipython中,默认编码为utf-8。

 1 In [1]: astr=你好,python
 2 
 3 In [2]: astr
 4 Out[2]: \xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8cpython
 5 
 6 In [3]: astr.encode(utf8)
 7 ----------------------------------------------------
 8 UnicodeDecodeError                        Traceback
 9 <ipython-input-3-cb3c3e44ee4d> in <module>()
10 ----> 1 astr.encode(utf8)
11 
12 UnicodeDecodeError: ascii codec cant decode byte
13 
14 In [4]: astr.decode(utf8).encode(utf8)
15 Out[4]: \xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8cpython
16 
17 In [5]: bstr=u你好,python
18 
19 In [6]: bstr
20 Out[6]: u\u4f60\u597d\uff0cpython
21 
22 In [7]: bstr.encode(utf8)
23 Out[7]: \xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8cpython

在python shell中,默认编码为命令行终端的默认编码,作者的是windows7 cmd环境,默认编码为gb2312。

 1 >>> astr=你好,python
 2 
 3 >>> astr
 4 \xc4\xe3\xba\xc3\xa3\xacpython
 5 
 6 >>> astr.encode(utf8)
 7 Traceback (most recent call last):
 8   File "<stdin>", line 1, in <module>
 9 UnicodeDecodeError: ascii codec cant decode byte 0xc4 in position 0: ordinal not in range(128)
10 
11 >>> astr.decode(utf8).encode(utf8)
12 Traceback (most recent call last):
13   File "<stdin>", line 1, in <module>
14   File "E:\Anaconda\envs\py27\lib\encodings\utf_8.py", line 16, in decode
15     return codecs.utf_8_decode(input, errors, True)
16 UnicodeDecodeError: utf8 codec cant decode byte 0xc4 in position 0: invalid continuation byte
17 
18 >>> astr.decode(gb2312).encode(utf8)
19 \xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8cpython
20 
21 >>> bstr=u你好,python
22 
23 >>> bstr
24 u\u4f60\u597d\uff0cpython
25 
26 >>> bstr.encode(utf8)
27 \xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8cpython

在python2中,字符以各个终端环境中的默认编码或者指定的编码形式存储,进行编码转换时,需要先将字符解码转为unicode形式,在编码为指定形式的编码字符。

python3中的字符编码

 在ipython中:

 1 In [1]: astr=你好,python
 2 
 3 In [2]: astr
 4 Out[2]: 你好,python
 5 
 6 In [3]: astr.encode(utf8)
 7 Out[3]: b\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8cpython
 8 
 9 In [4]: astr.decode(utf8).encode(utf8)
10 ---------------------------------------------------------------------------
11 AttributeError                            Traceback (most recent call last)
12 <ipython-input-4-2a9e1e602dd8> in <module>()
13 ----> 1 astr.decode(utf8).encode(utf8)

在python3 shell中:

 1 >>> astr=你好,python
 2 
 3 >>> astr
 4 你好,python
 5 
 6 >>> astr.encode(utf8)
 7 b\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8cpython
 8 
 9 >>> astr.decode(gb2312).encode(utf8)
10 Traceback (most recent call last):
11   File "<stdin>", line 1, in <module>
12 AttributeError: str object has no attribute decode

在python3中,字符默认是以unicode形式存储的。

 

python2和python3中字符编码区别

原文:https://www.cnblogs.com/pypypy/p/11836359.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!