[Python]编码声明
来源:互联网 发布:域名的ip地址查询 编辑:程序博客网 时间:2024/05/10 17:18
我们知道在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=<encoding name>
或者(使用流行编辑器中的格式化方式)
#!/usr/bin/python# -*- coding: <encoding name> -*-
或者
#!/usr/bin/python# vim: set fileencoding=<encoding name> :
不管怎么样,这些在第一行或者第二行的声明都要符合正则表达式
"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
...
以上几个例子充分说明了哪些是正确的写法,哪些是正确的写法
- python 中文编码声明
- python的编码声明
- python编码声明问题
- [Python]编码声明
- python中的编码声明
- Python编码声明与乱码
- Python文件编码的声明方法
- 关于python对程序编码的声明
- python中字符串:声明、编码、函数、格式化
- python 文件头的编码声明问题
- Python的编码声明 # -*- coding:utf-8 -*-
- 【Python的脸】——声明、文档字符串、编码风格
- python初学main函数 文档字符串 编码声明
- python中声明编码方式必须放在第一行
- python声明源文件编码格式、选择解释器
- Python 学习日记-01.中文编码声明# coding:UTF-8
- python 编码问题-文件编码格式和编码声明的作用
- Python中用encoding声明的文件编码和文件的实际编码之间的关系
- session的get()和load()有什么区别?
- Electricity
- 使用JPEGImageEncoder提示Access restriction:错误 解决方案
- 无需建工程编译ndk程序
- 去掉标头的方式
- [Python]编码声明
- poj 1186 方程的解数(线性探测再哈希)
- $.event
- 微信客服我是这样管理的
- 容斥原理1004 POJ 1091
- 安卓蓝牙如何查看和分析btsnoop.log
- 随时随地结束Activity
- CP15协处理器访问指令MCR/MRC解析
- 容斥原理1005 POJ 2773