chr() 等效返回一个字节对象,在 py3k 中 [英] chr() equivalent returning a bytes object, in py3k

查看:47
本文介绍了chr() 等效返回一个字节对象,在 py3k 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 2.x 具有 chr(),它将 0-255 范围内的数字转换为一个字节字符串,其中一个字符具有该数值,并且 unichr()code>,它将 0-0x10FFFF 范围内的数字转换为 Unicode 字符串,其中一个字符具有该 Unicode 代码点.Python 3.x 将 unichr() 替换为 chr(),以符合其Unicode 字符串是默认值"的政策,但我找不到任何可以完全执行的操作旧的 chr() 做到了.2to3 实用程序(来自 2.6)让 chr 单独调用,这通常是不正确的 :(

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 2to3 utility (from 2.6) leaves chr calls alone, which is not right in general :(

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

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

推荐答案

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

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.

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

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

这篇关于chr() 等效返回一个字节对象,在 py3k 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆