当我们在 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/