我应该在 Python 3 中使用编码声明吗? [英] Should I use encoding declaration in Python 3?

查看:43
本文介绍了我应该在 Python 3 中使用编码声明吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 3 默认对源代码文件使用 UTF-8 编码.我还应该在每个源文件的开头使用编码声明吗?像 # -*- 编码:utf-8 -*-

Python 3 uses UTF-8 encoding for source-code files by default. Should I still use the encoding declaration at the beginning of every source file? Like # -*- coding: utf-8 -*-

推荐答案

因为默认 UTF-8,你只需要在偏离默认的时候使用那个声明,或者如果你依赖在其他工具(如您的 IDE 或文本编辑器)上使用该信息.

Because the default is UTF-8, you only need to use that declaration when you deviate from the default, or if you rely on other tools (like your IDE or text editor) to make use of that information.

换句话说,就 Python 而言,只有当您想使用不同的编码时,才必须使用该声明.

In other words, as far as Python is concerned, only when you want to use an encoding that differs do you have to use that declaration.

其他工具,例如您的编辑器,可以支持类似的语法,这就是为什么 PEP 263 规范允许在语法上具有相当大的灵活性(它必须是注释,文本coding 必须在那里,后跟 :>= 字符和可选的空格,后跟可识别的编解码器).

Other tools, such as your editor, can support similar syntax, which is why the PEP 263 specification allows for considerable flexibility in the syntax (it must be a comment, the text coding must be there, followed by either a : or = character and optional whitespace, followed by a recognised codec).

请注意,它仅适用于 Python 读取源代码的方式.它不适用于执行该代码,因此不适用于打印、打开文件或任何其他 I/O 操作在字节和 Unicode 之间转换的方式.有关 Python、Unicode 和编码的更多详细信息,我强烈建议您阅读 Python Unicode HOWTO 或 Ned 非常彻底的Pragmatic Unicode 谈话巴切尔德.

Note that it only applies to how Python reads the source code. It doesn't apply to executing that code, so not to how printing, opening files, or any other I/O operations translate between bytes and Unicode. For more details on Python, Unicode, and encodings, I strongly urge you to read the Python Unicode HOWTO, or the very thorough Pragmatic Unicode talk by Ned Batchelder.

这篇关于我应该在 Python 3 中使用编码声明吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆