python - 何时使用 utf8 作为 py 文件中的 header

标签 python utf-8

一些来自下载代码的源文件具有以下 header

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

我知道 utf-8 编码是什么,但为什么需要它作为 python 源文件中的 header ?

最佳答案

任何你需要在代码中使用非 ascii 字符的地方,例如:

ă 

解释器会提示他不理解那个字符。

通常这发生在您定义常量时。

例子: 添加到x.py

print 'ă'

然后启动一个python控制台

import x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "x.py", line 1
 SyntaxError: Non-ASCII character '\xc4' in file x.py on line 1, 
   but no encoding declared;
   see http://www.python.org/peps/pep-0263.html for details

关于python - 何时使用 utf8 作为 py 文件中的 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13807748/

相关文章:

python - 使用 numpy/python 将具有相同索引的值相加

mysql - 为什么 ruby​​ 检测不到无效编码而 mysql 检测到?

perl - 如何确定字符串的字符集?

c++ - 如何将 CSV 文件保存为 UTF-8

utf-8 - clojure 和戒指 : utf-8 in responses comes through as '?'

java - Java 使用 UTF-8 还是 UTF-16 编码?

python - Python中nginx和uWSGI获取认证数据

python - 用于缩放的 OpenShift REST API,无效字符 's' 正在寻找值的开头

python - 参数解包是否使用迭代或项目获取?

python - Numpy 唯一 : count for values also not in array?