在Python中,何时chr(ord(c))不等于c?

5

我正在阅读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,获取每个字符的整数序号并将其转换回一个字符字符串。但是这样做有什么意义呢?

Python的版本可能在这里很重要。在Python2中,ord接受unicode字符作为输入,但chr只能从int转换为ASCII,因此可能会利用一些奇怪的东西? - user2201041
2
指出您在代码中看到那一行会有所帮助。没有上下文,我们无法做太多事情。我假设您是指Ansible模块中的代码...那里的注释可能会有用。 - Jeff Mercado
1
@JeffMercado 是的,它在ansible后端源代码中。我已经阅读了评论,但作者为什么要使用它?它是否等同于 out['stdout'].encode('ascii') - satoru
1个回答

5
c 是 Unicode 特殊字符(无法用 ASCII 编码)时:
>>> ord(u'\u2020')
8224
>>> chr(ord(u'\u2020'))
ValueError: chr() arg not in range(256)

这只适用于Python2,因为在Python3中,unichr已被删除,chr作为unichr的替代。这似乎是一个不寻常的行为,因为对于任何非英语环境,它通常会引发特定于可执行文件的意外错误。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接