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.
In Python, we can use bin() or format() to convert an integer into a binary string representation.
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.
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”.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With