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

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

问题描述

Python 3默认情况下对源代码文件使用UTF-8编码.我还应该在每个源文件的开头使用编码声明吗?就像# -*- coding: 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 读取源代码的方式.它不适用于执行该代码,因此不适用于在字节和Unicode之间进行打印,打开文件或任何其他I/O操作的方式.有关Python,Unicode和编码的更多详细信息,强烈建议您阅读 Python Unicode HOWTO ,或者Ned的非常详尽的 实用Unicode 对话 Batchelder.

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天全站免登陆