什么时候chr(ord(c))不等于Python中的c?

2024-04-20 00:35:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在阅读Ansible模块中testinfra的源代码。我发现了以下几行代码:

    # Ansible return an unicode object but this is bytes ...
    # A simple test case is:
    # >>> assert File("/bin/true").content == open("/bin/true").read()
    stdout_bytes = b"".join((chr(ord(c)) for c in out['stdout']))
    stderr_bytes = b"".join((chr(ord(c)) for c in out['stderr']))

它迭代stdout,获取每个字符的整数序数并将其转换回一个单字符字符串。但有什么意义呢?在


Tags: 模块intrueforbytesbinisstderr
2条回答

当c是8位字符串时。从docs for ord()

[returns] the value of the byte when the argument is an 8-bit string

chr()然后将其转换为相应的字符。基本上就是把字节转换成一个字符,就像评论说的那样。在

c是unicode特定字符时(不能用ASCII编码):

>>> ord(u'\u2020')
8224
>>> chr(ord(u'\u2020'))
ValueError: chr() arg not in range(256)

这只在Python2中有效,正如在Python3中一样,unichr被删除,chr充当unichr。对于这样一个库来说,这似乎是不寻常的行为,因为它通常会抛出一个意外的错误,对于任何非英语语言环境都是可执行的。在

相关问题 更多 >