关于python对程序编码的声明

python2在执行python代码时读取文件默认使用ASCII编码,因此我们经常看到在代码的前边有如下声明:


# -*- coding:utf-8 -*- 


看起来很呆萌,对不对。为什么要有此声明,python的PEP中有说明  http://www.python.org/dev/peps/pep-0263/

并且必须将编码注释放在第一行或者第二行。


# coding=<encoding name>


or (using formats recognized by popular editors)


#!/usr/bin/python

# -*- coding: <encoding name> -*-


当然还支持其他声明方式。当然呆萌的写法大家都喜欢用咯。


下面是支持和不支持的写法说明,供大家参考。另外python3 的默认读取代码采用的是unicode,所以python3 该声明可选,如果需要其他编码的话,还是可以采用上述写法的。
Examples

These are some examples to clarify the different styles for defining the source code encoding at the top of a Python source file:
    1. With interpreter binary and using Emacs style file encoding comment:


          #!/usr/bin/python

          # -*- coding: latin-1 -*-
          import os, sys
          ...


          #!/usr/bin/python
          # -*- coding: iso-8859-15 -*-
          import os, sys
          ...


          #!/usr/bin/python
          # -*- coding: ascii -*-
          import os, sys
          ...

2. Without interpreter line, using plain text:

          # This Python file uses the following encoding: utf-8
          import os, sys
          ...

3. Text editors might have different ways of defining the file's
       encoding, e.g.

          #!/usr/local/bin/python
          # coding: latin-1
          import os, sys
          ...

4. Without encoding comment, Python's parser will assume ASCII text:

          #!/usr/local/bin/python
          import os, sys
          ...

5. Encoding comments which don't work:
       Missing "coding:" prefix:

          #!/usr/local/bin/python
          # latin-1
          import os, sys
          ...

       Encoding comment not on line 1 or 2:

          #!/usr/local/bin/python
          #
          # -*- coding: latin-1 -*-
          import os, sys
          ...

       Unsupported encoding:

          #!/usr/local/bin/python
          # -*- coding: utf-42 -*-
          import os, sys
          ...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值