gpt4 book ai didi

python - Python/Django 中的 Unicode 与 UTF-8 混淆?

转载 作者:IT老高 更新时间:2023-10-28 22:03:10 44 4
gpt4 key购买 nike

我在 Django tutorial 中偶然发现了这段话。 :

Django models have a default str() method that calls unicode() and converts the result to a UTF-8 bytestring. This means that unicode(p) will return a Unicode string, and str(p) will return a normal string, with characters encoded as UTF-8.

现在,我很困惑,因为 afaik Unicode 不是任何特定的表示形式,那么 Python 中的“Unicode 字符串”是什么?这是否意味着UCS-2?谷歌搜索出现this "Python Unicode Tutorial"大胆地指出

Unicode is a two-byte encoding which covers all of the world's common writing systems.

这是完全错误的,是吗?我多次被字符集和编码问题弄糊涂了,但是在这里我很确定我正在阅读的文档很困惑。当 Python 给我一个“Unicode 字符串”时,有人知道它发生了什么吗?

最佳答案

what is a "Unicode string" in Python? Does that mean UCS-2?

Python 中的 Unicode 字符串在内部存储为 UCS-2(固定长度 16 位表示,与 UTF-16 几乎相同)或 UCS-4/UTF-32(固定长度 32 位表示)。这是一个编译时选项;在 Windows 上,它始终是 UTF-16,而许多 Linux 发行版为其 Python 版本设置了 UTF-32(“宽模式”)。

您通常不应该关心:您会将 Unicode 代码点视为字符串中的单个元素,并且您不知道它们是存储为两个字节还是四个字节。如果您在 UTF-16 构建中并且需要处理基本多语言平面之外的字符,那么您将做错,但这仍然非常罕见,真正需要额外字符的用户应该编译宽版本。

plain wrong, or is it?

是的,这是完全错误的。公平地说,我认为该教程相当陈旧。它可能早于广泛的 Unicode 字符串,如果不是 Unicode 3.1(在基本多语言平面之外引入字符的版本)。

Windows 习惯使用术语“Unicode”来表示 NT 内部使用的 UTF-16LE 编码,还有一个额外的混淆来源。来自 Microsoftland 的人可能经常会复制这种具有误导性的习惯。

关于python - Python/Django 中的 Unicode 与 UTF-8 混淆?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22149/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com