How to define a binary string in Python in a way that works with both py2 and py3?

I am writing a module that should work in both Python 2 and 3, and I need to define a binary string.

Usually it will be something like data = b'abc', but this code does not work on Python 2.5 with invalid syntax.

How can I write the above code in a way that will work in all versions of Python 2.5+

Note: this should be binary(it can contain any characters, 0xFF), this is very important.

+5
source share
3 answers

I would recommend the following:

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 ( ).

+4

ASCII, encode. str Python 2 ( b'abc') a bytes Python 3:

'abc'.encode('ascii')

, , , , 'rb' .

+1

64.

base64:

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

, b Python, .

b. , py2 py3.

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

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

As an alternative to the two above steps, you can do the same with hexadecimal data, you can do

import binascii
x = '80FF'
binascii.unhexlify(x) # `bytes()` in 3.x, `str()` in 2.x
-3
source

All Articles