为什么空字符串 '' 在 utf-16 中编码为 2 个字节,而在 utf-8 或 ascii 中编码为 0 个字节?

Why is an empty string '' encoded into 2 bytes in utf-16 but 0 bytes in utf-8 or ascii?

我刚开始学习 python 中的字符串编码,在稍微弄乱之后,我对空字符串 ('') 的大小在 utf 8 和 ascii 中为 0 这一事实感到困惑但不知何故 2 in utf 16?怎么会?

print(len(''.encode('utf16'))) # is 2
print(len(''.encode('utf8'))) # is 0

我想问题的很大一部分是我不明白 utf 16 是如何工作的。我不明白为什么在 utf 16 中编码 'spam' 会是 10 个字节长而不是 8 个字节(每个字符 2 个字节(16 位))。我假设 utf 16 中需要 2 个字节作为填充或其他任何字符串的默认值?

*编辑

我对 UTF 8 或 UTF 16 的工作原理和存储每个字符的不同之处并不感到困惑。我很困惑如何将缺少任何字符(空字符串)存储在 UTF 16 中的 2 个字节中,但在 UTF 8 中有 0 个字节。(而不是 1 个字节或两者都为 0)

link 没有回答我的问题。

默认情况下,Python 在编码为 UTF-16 时包含 Byte Order Mark,但在编码为 UTF-8 时不包含。

>>> ''.encode('utf16')
b'\xff\xfe'
>>> ''.encode('utf8')
b''

您可以通过使用 BE (Big-Endian) 或 LE (Little-Endian) 后缀显式指定字节顺序来抑制 BOM。

>>> ''.encode('utf-16-le')
b''