7

我正在编写一个应该在 Python 2 和 3 中工作的模块,我需要定义一个二进制字符串。

通常这会是这样的,data = b'abc'但是这段代码在 Python 2.5 上失败,语法无效。

如何以适用于所有 Python 2.5+ 版本的方式编写上述代码

注意:这个必须是binary(可以包含任何类型的字符,0xFF),这个很重要。

4

3 回答 3

6

我会推荐以下内容:

from six import b

当然,这需要六个模块。如果你不想这样,这里有另一个版本:

import sys
if sys.version < '3':
    def b(x):
        return x
else:
    import codecs
    def b(x):
        return codecs.latin_1_encode(x)[0]

更多信息

这些解决方案(基本上相同)工作,干净,尽可能快,并且可以支持所有 256 字节值(这里没有其他解决方案可以)。

于 2011-10-13T20:16:05.220 回答
2

如果字符串只有 ASCII 字符,请调用encode. 这将为您提供strPython 2 中的 a(就像b'abc')和bytesPython 3 中的 a:

'abc'.encode('ascii')

如果没有,不要将二进制数据放入源中,而是创建一个数据文件,打开它'rb'并从中读取。

于 2011-10-13T13:57:40.567 回答
-3

You could store the data base64-encoded.

First step would be to transform into base64:

>>> import base64
>>> base64.b64encode(b"\x80\xFF")
b'gP8='

This is to be done once, and using the b or not depends on the version of Python you use for it.

In the second step, you put this byte string into a program without the b. Then it is ensured that it works in py2 and py3.

import base64
x = 'gP8='
base64.b64decode(x.encode("latin1"))

gives you a str '\x80\xff' in 2.6 (should work in 2.5 as well) and a b'\x80\xff'in 3.x.

Alternatively to the two steps above, you can do the same with hex data, you can do

import binascii
x = '80FF'
binascii.unhexlify(x) # `bytes()` in 3.x, `str()` in 2.x
于 2011-10-13T14:11:12.607 回答