Python编码相关

1、#coding=utf-8的作用

  作用是这个文件代码的编码格式,如果没有声明代码中不能出现中文字符,包括注释中也不能出现。否则会报错SyntaxError: Non-ASCII character。

2、sys.setdefaultencoding('utf-8')的作用

  可以使用sys.getdefaultencoding()获取系统编码格式。python2和python3的默认编码格式是不相同的,2是ascii码,3默认是utf-8。

  如果不设置默认的编码,使用中文的时候,在2中重新去encode的时候就会报错。因为ascii中没有中文,而encode的时候python会自动要先进行decode,而decode解码的方式会使用默认的系统编码。这样,中文就会出错了。因此,可以指定解码的方式,如s.decode('utf-8').encode('gb2312')。

  或者在代码开始处加:

  import sys
  reload(sys)
  sys.setdefaultencoding('utf-8')

报错信息
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 0: ordinal not in range(128)
s = '中文字符' 
s.encode('gb2312') 

 3、reload(sys)的作用

  因为,在sys加载后,setdefaultencoding方法被删除了,所以我们要通过重新导入sys来设置系统编码。如果,不reload会报下面的错误。

AttributeError: 'module' object has no attribute 'setdefaultencoding'
原文地址:https://www.cnblogs.com/zhaoyihao/p/6644069.html