当使用UTF8时,当Pprint显示时,为什么有些字符会转换为 U符号



这是一个控制台演示:

>>> x = "a b"
>>> x
'au200ab'
>>> repr( x )
"'a\u200ab'"

因此,Pprint似乎正在使用与打印字符串相同的技术。

公认的是A&amp之间的白空间特征;b在与x结合的初始值中,实际上是u 200a。但是,当使用UTF-8输入和输出编码时,为什么要将任何字符转换为 u表示符号?

问题2当然,如何以这种方式了解整个字符集?

问题3当然,如何抑制这种行为?

pprint打印您传递的对象的表示形式。从文档

PPRINT模块提供了"漂亮印刷"任意的功能 Python数据结构的形式可以用作输入 解释器。

和"可以用作解释器输入的表单"意味着您获得对象的表示,即其__repr__方法返回什么。

如果要使用其__str__方法而不是__repr__打印字符串,则不要使用pprint


这是一个python 3代码段,寻找使用u逃生代码表示的字符:

for i in range(1500):
    c = chr(i)
    r = repr(c)
    if r'u' in r:
        print('{0:4} {0:04x} {1} {2}'.format(i, r, c))

输出

 888 0378 'u0378' ͸
 889 0379 'u0379' ͹
 896 0380 'u0380' ΀
 897 0381 'u0381' ΁
 898 0382 'u0382' ΂
 899 0383 'u0383' ΃
 907 038b 'u038b' ΋
 909 038d 'u038d' ΍
 930 03a2 'u03a2' ΢
1328 0530 'u0530' ԰
1367 0557 'u0557' ՗
1368 0558 'u0558' ՘
1376 0560 'u0560' ՠ
1416 0588 'u0588' ֈ
1419 058b 'u058b' ֋
1420 058c 'u058c' ֌
1424 0590 'u0590' ֐
1480 05c8 'u05c8' ׈
1481 05c9 'u05c9' ׉
1482 05ca 'u05ca' ׊
1483 05cb 'u05cb' ׋
1484 05cc 'u05cc' ׌
1485 05cd 'u05cd' ׍
1486 05ce 'u05ce' ׎
1487 05cf 'u05cf' ׏

请注意,CodePoints> 0xffff使用U逃生代码表示。

for i in range(65535, 65600):
    c = chr(i)
    r = repr(c)
    if r'u' in r.lower():
        print('{0:4} {0:04x} {1} {2}'.format(i, r, c))

输出

65535 ffff 'uffff' �
65548 1000c 'U0001000c' 𐀌
65575 10027 'U00010027' 𐀧
65595 1003b 'U0001003b' 𐀻
65598 1003e 'U0001003e' 𐀾

我终于找到了解释它的文档。来自Python Unicode文档:

int py_unicode_isprintable(py_unicode ch)

Return 1 or 0 depending on whether ch is a printable character. Nonprintable characters are those characters defined in the Unicode character database as “Other” or “Separator”, excepting the ASCII space (0x20) which is considered printable. (Note that printable characters in this context are those which should not be escaped when repr() is invoked on a string. It has no bearing on the handling of strings written to sys.stdout or sys.stderr.)

它部分回答了第一个问题(事实,而不是原因),并导致问题2的确切答案。

Unicode空间分隔符字符

我想在视觉上明确的愿望是事实的原因……所有这些分隔符角色看起来"相同"(白空间)。如果您要检查纸质日志,这可能很重要,但是如果在线检查它,将/粘贴复制到十六进制的显示工具,或者对此非常有用的Unicode解码器肯定是足够的,而不会中断文本的流程。使用分离器并不重要(我认为这是大多数非纸时间)。

问题3显然可以通过两种方式之一来完成:创建具有不同 repr (破坏现有代码)或创建具有格式函数的PPRINT的STR的子类,以避免调用<调用> repr for str,但直接包含值。

最新更新