我正在编写一个应该在 Python 2 和 3 中工作的模块,我需要定义一个二进制字符串。
通常这会是这样的,data = b'abc'
但是这段代码在 Python 2.5 上失败,语法无效。
如何以适用于所有 Python 2.5+ 版本的方式编写上述代码
注意:这个必须是binary
(可以包含任何类型的字符,0xFF),这个很重要。
我正在编写一个应该在 Python 2 和 3 中工作的模块,我需要定义一个二进制字符串。
通常这会是这样的,data = b'abc'
但是这段代码在 Python 2.5 上失败,语法无效。
如何以适用于所有 Python 2.5+ 版本的方式编写上述代码
注意:这个必须是binary
(可以包含任何类型的字符,0xFF),这个很重要。
如果字符串只有 ASCII 字符,请调用encode
. 这将为您提供str
Python 2 中的 a(就像b'abc'
)和bytes
Python 3 中的 a:
'abc'.encode('ascii')
如果没有,不要将二进制数据放入源中,而是创建一个数据文件,打开它'rb'
并从中读取。
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