python编码问题明白了

核心点: 

1. 在现在计算机系统通用的字符编码工作方式:在计算机内存中,统一使用Unicode编码,当需要保存到硬盘或需要传输时,可以转换为UTF-8编码。

2. decode()方法将其他编码字符转化为Unicode编码字符。encode()方法将Unicode编码字符转化为其他编码字符。

3. ASCII码仅仅能处理英文,GB2312处理中文,全球统一有了Unicode,为了提高Unicode存储和传输性能,产生了UTF-8,它是Unicode的一种实现形式。

4. Python2 解析器使用的默认解析编码是 ASCII,可以sys.setdefaultencoding() 设置成 utf-8.

5. # coding=utf-8 提示编译器这个文件是 utf-8编码, 但你一定要保证文件确实是这个编码噢... 

6. a = '卧室门是中华儿女',  a.encode("utf-8") 等价于 a.decode(defaultencoding).encode("utf-8") , 所以会报错.   【chardet.detect(a)  GB2312;  a.decode('GB2312').encode('utf-8')】  

# 以下代码在Windows系统  CMD+R python之后的命令行执行. 
>>> d = '思路发加上的'

>>> chardet.detect(d)
{'confidence': 0.99, 'language': 'Chinese', 'encoding': 'GB2312'}

>>> d
'\xcb\xbc\xc2\xb7\xb7\xa2\xbc\xd3\xc9\xcf\xb5\xc4'



>>> d.encode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xcb in position 0: ordinal not in range(128)

>>> d.decode('GB2312').encode('utf-8')
'\xe6\x80\x9d\xe8\xb7\xaf\xe5\x8f\x91\xe5\x8a\xa0\xe4\xb8\x8a\xe7\x9a\x84'

>>> d.decode('GB2312')
u'\u601d\u8def\u53d1\u52a0\u4e0a\u7684'

>>> d.decode('GB2312')
u'\u601d\u8def\u53d1\u52a0\u4e0a\u7684'

>>> d.decode('GB2312').encode('GB2312')
'\xcb\xbc\xc2\xb7\xb7\xa2\xbc\xd3\xc9\xcf\xb5\xc4'

>>> d.encode('GB2312')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xcb in position 0: ordinal not in range(128)

>>>

  

 参考:

https://blog.csdn.net/apache0554/article/details/53889253 

https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431664106267f12e9bef7ee14cf6a8776a479bdec9b9000  

猜你喜欢

转载自www.cnblogs.com/huiming/p/9415461.html
今日推荐