Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Usually this would be something like data = b'abc' but this code code fails 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 has to be binary (it can contain any kind of characters, 0xFF), this is very important.

like image 925
sorin Avatar asked Oct 13 '11 13:10

sorin


People also ask

How do you represent a binary string in Python?

In Python, we can use bin() or format() to convert an integer into a binary string representation.

Are Python 2 and 3 compatible with each other?

The latest stable version is Python 3.9 which was released in 2020. The nature of python 3 is that the changes made in python 3 make it incompatible with python 2. So it is backward incompatible and code written in python 3 will not work on python 2 without modifications.

How do you mix strings in Python?

The + operator lets you combine two or more strings in Python. This operator is referred to as the Python string concatenation operator. The + operator should appear between the two strings you want to merge. This code concatenates, or merges, the Python strings “Hello ” and “World”.


2 Answers

I would recommend the following:

from six import b

That requires the six module, of course. If you don't want that, here's another version:

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

More info.

These solutions (essentially the same) work, are clean, as fast as you are going to get, and can support all 256 byte values (which none of the other solutions here can).

like image 64
Lennart Regebro Avatar answered Sep 28 '22 15:09

Lennart Regebro


If the string only has ASCII characters, call encode. This will give you a str in Python 2 (just like b'abc'), and a bytes in Python 3:

'abc'.encode('ascii')

If not, rather than putting binary data in the source, create a data file, open it with 'rb' and read from it.

like image 22
Petr Viktorin Avatar answered Sep 28 '22 15:09

Petr Viktorin