Python chr() 等效返回一个字节对象,在 py3k 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4523505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:07:33  来源:igfitidea点击:

chr() equivalent returning a bytes object, in py3k

pythonunicodepython-3.x

提问by zwol

Python 2.x has chr(), which converts a number in the range 0-255 to a byte string with one character with that numeric value, and unichr(), which converts a number in the range 0-0x10FFFF to a Unicode string with one character with that Unicode codepoint. Python 3.x replaces unichr()with chr(), in keeping with its "Unicode strings are default" policy, but I can't find anything that does exactly what the old chr()did. The 2to3utility (from 2.6) leaves chrcalls alone, which is not right in general :(

Python 2.x 具有chr(),它将 0-255 范围内的数字unichr()转换为具有该数值的一个字符的字节字符串,以及,它将 0-0x10FFFF 范围内的数字转换为具有该 Unicode 的一个字符的 Unicode 字符串代码点。Python 3.x 替换unichr()chr(),与它的“Unicode 字符串是默认的”策略保持一致,但我找不到与旧版本完全相同的任何东西chr()。该2to3实用程序(来自 2.6)不理会chr调用,这通常是不正确的:(

(This is for parsing and serializing a file format which is explicitly defined in terms of 8-bit bytes.)

(这是用于解析和序列化以 8 位字节显式定义的文件格式。)

采纳答案by Guido U. Draheim

Consider using bytearray((255,)) which works the same in Python2 and Python3. In both Python generations the resulting bytearray-object can be converted to a bytes(obj) which is an alias for a str() in Python2 and real bytes() in Python3.

考虑使用 bytearray((255,)) ,它在 Python2 和 Python3 中的工作原理相同。在两代 Python 中,生成的 bytearray 对象都可以转换为 bytes(obj),它是 Python2 中 str() 和 Python3 中真实 bytes() 的别名。

# Python2
>>> x = bytearray((32,33))
>>> x
bytearray(b' !')
>>> bytes(x)
' !'

# Python3
>>> x = bytearray((32,33))
>>> x
bytearray(b' !')
>>> bytes(x)
b' !'

回答by Mark Byers

Try the following:

请尝试以下操作:

b = bytes([x])

For example:

例如:

>>> bytes([255])
b'\xff'

回答by SangYoung Lee

>>> import struct
>>> struct.pack('B', 10)
b'\n'
>>> import functools
>>> bchr = functools.partial(struct.pack, 'B')
>>> bchr(10)
b'\n'

回答by youfu

In case you want to write Python 2/3 compatible code, use six.int2byte

如果您想编写 Python 2/3 兼容代码,请使用 six.int2byte

回答by Ecir Hana

Yet another alternative (Python 3.5+):

另一种选择(Python 3.5+):

>>> b'%c' % 65
b'A'

回答by Glushiator

simple replacement based on small range memoization (should work on 2 and 3), good performance on CPython and pypy

基于小范围记忆的简单替换(应该适用于 2 和 3),在 CPython 和 pypy 上性能良好

binchr = tuple([bytes(bytearray((b,))) for b in range(256)]).__getitem__

binchr(1) -> b'\x01'