python 编码声明 encoding_[Python]编码声明:是coding:utf-8还是coding=utf-8呢

PEP 263 -- Defining Python Source Code Encodings | Python.org https://www.python.org/dev/peps/pep-0263/

[Python]编码声明:是coding:utf-8还是coding=utf-8呢_Python_orangleliu 笔记本-CSDN博客 https://blog.csdn.net/orangleliu/article/details/8755461

我们知道在Python源码的头文件中要声明编码方式,如果你不只是会用到ascii码,很多人都写得都有点差别:

#coding=utf-8

#coding:utf-8

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

那么怎样写才是有效地呢,哪些优势无效的呢?

可以查看下http://www.python.org/dev/peps/pep-0263/的解释

粗略的看下:

概要:

这个PEP的目的是介绍在一个Python源文件中如何声明编码的语法。随后Python解释器会在解释文件的时候用到这些编码信息。最显著的是源文件中对Unicode的解释,使得在一个能识别Unicode的编辑器中使用如FUT-8编码成为可能

怎么声明呢?

如果在Python中我们并没有声明别的编码方式,就是以ASCII编码作为标准编码方式的

为了定义源文件的编码方式,一个魔法是的声明应当被放在这个文件的第一行或者是第二行例如:

#coding=

或者(使用流行编辑器中的格式化方式)

#!/usr/bin/python

# -*- coding: -*-

或者

#!/usr/bin/python

# vim: set fileencoding= :

不管怎么样,这些在第一行或者第二行的声明都要符合正则表达式

"coding[:=]\s*([-\w.]+)"

所以我们就可以知道为什么使用冒号或者等号都可以了,如果声明的编码python不能识别就会报错

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

...

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值