gpt4 book ai didi

python - 如何解释 format(n, 'c' ) 超出 ASCII 的结果?

转载 作者:太空狗 更新时间:2023-10-30 02:29:21 25 4
gpt4 key购买 nike

考虑以下示例:

format(97, 'c')
format(6211, 'c')

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

string format specification指出:

'c': Character. Converts the integer to the corresponding unicode character before printing.

那么6211不应该映射到它的Unicode字符吗?

相关系统信息:Fedora 22 上的 CPython 2.7.10。

最佳答案

您看到的是 Issue 7267 - format method: c presentation type broken in 2.7 .

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

>>> format(256,'c')
'\x00'

根据问题,他们说解决方法是使用 Python 3,其中字符串是 unicode,因此 Python 3.x 中不存在问题。

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

>>> unichr(0x6211)
u'\u6211'
>>> print(unichr(0x6211))

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

关于python - 如何解释 format(n, 'c' ) 超出 ASCII 的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32859270/

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