【发布时间】:2017-11-05 04:31:33
【问题描述】:
Unicode 字符串是一个代码点序列
Unicode 字符串表示为
unicode类型的实例
>>> ThisisNotUnicodeString = 'a정정????' # What is the memory representation?
>>> ThisisNotUnicodeString
'a\xec\xa0\x95\xec\xa0\x95\xf0\x9f\x92\x9b'
>>> type(ThisisNotUnicodeString)
<type 'str'>
>>> a = u'a정정????' # Which encoding technique used to represent in memory? utf-8?
>>> a
u'a\uc815\uc815\U0001f49b'
>>> type(a)
<type 'unicode'>
>>> b = unicode('a정정????', 'utf-8')
>>> b
u'a\uc815\uc815\U0001f49b'
>>> c = unicode('a정정????', 'utf-16')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/encodings/utf_16.py", line 16, in decode
return codecs.utf_16_decode(input, errors, True)
UnicodeDecodeError: 'utf16' codec can't decode byte 0x9b in position 10: truncated data
>>>
问题:
1) ThisisNotUnicodeString 是字符串文字。尽管 ThisisNotUnicodeString 不是 unicode 文字,但哪种编码技术用于在内存中表示 ThisisNotUnicodeString?因为应该有一些编码技术来表示内存中的정 或???? 字符。
2) 哪种编码技术用于在内存中表示 unicode 文字 a? UTF-8?如果是,如何知道占用的字节数?
3) 为什么c 没有在内存中表示,使用utf-16 技术?
【问题讨论】:
-
“内存表示”是什么意思?
-
这可能不是在某些控制台中输入而是在具有指定编码的源文件中输入,然后您可以使用它。
-
a = u'a정정????'是根据终端编码进行解码的。见sys.stdin.encoding。我们知道终端编码是 UTF-8,因为随后b = unicode('a정정????', 'utf-8')成功。c = unicode('a정정????', 'utf-16')因此失败,原因很明显,UTF-8 字节字符串不能被解码为 UTF-16。这两种编码完全不同。 -
unicode的内部格式取决于构建。 Windows 和一些 Unix 系统上的 Python 2 使用内部类似于 UTF-16 的窄构建,但对于非 BMP 字符串会损坏,因为它将代理对计为字符串长度中的两个字符。大多数 Unix 系统使用宽版本,它将每个 Unicode 序数存储为一个 4 字节整数。 -
@eryksun 它从来不是 UTF-16。 UCS-2 或 UCS-4。
标签: python python-2.7 unicode