【问题标题】:Is there any python "utf-8" string constant?是否有任何 python“utf-8”字符串常量?
【发布时间】:2017-10-21 21:29:49
【问题描述】:

我想使用“utf-8”字符串常量,因为在“UTF-8”、“UTF8”、“utf8”、“utf-8”、“utf-8”之间进行选择总是让我感到困惑, "utf_8"

python 文档中的所有代码示例的语法如下:

with io.open("/tmp/a.txt", "w", encode="utf-8") as file_cursor:
    file_cursor.write(text)

谁能告诉我为什么会这样,也许是一些最佳实践,zends ...?

我想在 IDE 中使用代码建议来实现类似:

with io.open("/tmp/a.txt", "w", encode=ENCODINGS.UTF8) as file_cursor:
    file_cursor.write(text)  

python 核心中是否有开箱即用的标准常量?

【问题讨论】:

  • 为什么重要? python 接受以上所有内容,如果需要,您甚至可以使用Utf - 8- -uTf _#8_ - -。如果您要为编码定义常量,您最终可能会得到 standard encodings 的名称,并且它们的值等于它们的名称,这(至少对我而言)似乎毫无意义且不符合 Python 标准,现在您需要导入这些常量在你可以使用它们之前从某个地方开始,它不会增加任何价值。

标签: python encoding utf-8


【解决方案1】:

你可以使用:

import encodings

encodings.utf_8.getregentry().name

给出'utf-8'

【讨论】:

  • 在 Python 3.9.6 中,我从pylint 得到“'CodecInfo' 的实例没有'name' 成员”(大概是因为CodecInfo 是这个奇怪的tuple 子类,具有很多属性。那似乎是false positive
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-18
  • 2021-08-13
  • 1970-01-01
  • 2016-10-23
  • 2021-02-14
相关资源
最近更新 更多