python - '# -*- coding: utf-8 -*-' 也是 Python 中的注释吗?

标签 python unicode encoding utf-8 comments

当我们在 Python 中使用 # 插入注释时,那么 Python 是如何处理的:

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

不同?

最佳答案

是的,它也是一个评论。 并且如果该注释的内容位于文件的顶部,即前两行,则该注释的内容具有特殊含义。

来自 Encoding declarations documentation :

If a comment in the first or second line of the Python script matches the regular expression coding[=:]\s*([-\w.]+), this comment is processed as an encoding declaration; the first group of this expression names the encoding of the source code file. The encoding declaration must appear on a line of its own. If it is the second line, the first line must also be a comment-only line.

请注意,就注释而言,应该使用什么编解码器来读取文件并不重要。 Python 通常会忽略 # 标记之后的 everything,并且在所有接受的源代码编解码器中,#、编码声明和行分隔符都被精确编码相同,因为它们都是 ASCII 的超集。所以解析器所要做的就是读取一行,扫描注释中的特殊文本,如果需要读取另一行,扫描注释,然后配置解析器根据给定的编解码器读取数据。

鉴于注释必须是文件中的第一或第二(如果是第二行,第一行也必须是注释),这是完全安全的,因为配置的编解码器只能使无论如何都与非注释行有所不同。

关于python - '# -*- coding: utf-8 -*-' 也是 Python 中的注释吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41680533/

相关文章:

sql-server - 在 SQL Server 2012 中将 varbinary() 转换为 varchar(max) 时如何编码特定语言的字符?

python - IDLE Shell 中的 "== RESTART <path> =="是什么意思?

python - Python 列表中的交集

python - 尝试保持发现字典的顺序时发生错误

ruby - 为什么我的 JSON 提要中的这个 Unicode/UTF-8 "En Dash"字符在我下载时会被损坏?

Python:如何将unicode与变量内的unicode进行比较

javascript - Django 动态字段 - 无法从模板中添加的多个行获取数据

Java - PDFBox 1.8.9 unicode 文本文件转 pdf

php - 使用正确的编码读取文件

json - 如何确定 JSON.stringify() 使用哪种编码?