如何解释格式(n,'c')超出ASCII的结果?

Nai*_*ree 4 python python-2.7

请考虑以下示例:

format(97, 'c')
format(6211, 'c')
Run Code Online (Sandbox Code Playgroud)

第一个产出'a'显然是正确的; 然而,第二个输出'C'我不明白为什么.

字符串格式规范规定:

'c':性格.在打印之前将整数转换为相应的unicode字符.

所以不6211应该映射到中文的Unicode字符?

相关的sysinfo:CPython 2.7.10,在Fedora 22上.

Ana*_*mar 6

您将看到问题7267 - 格式方法:c在2.7中打破了演示文稿类型.

问题是format(int, 'c')内部调用int.__format__('c'),它返回一个str值(Python 2.x中的字节),因此它总是在范围(0,256).因此对于像256这样的值,它会回到原点0.示例 -

>>> format(256,'c')
'\x00'
Run Code Online (Sandbox Code Playgroud)

根据这个问题,他们说修复将是使用Python 3,其中字符串是unicode,因此Python 3.x中没有问题.

我能想到的唯一解决方法是使用unichr()-

>>> unichr(0x6211)
u'\u6211'
>>> print(unichr(0x6211))
?
Run Code Online (Sandbox Code Playgroud)

虽然请注意,6211是一个整数,它不是你要找的unicode字符,它映射到0x1843.您正在寻找的是0x6211十六进制值,它映射到?,即format(0x6211,'c')在Python 3.x中.