s=str(binary)

John Machin sjmachin at lexicon.net
Mon Jan 19 23:23:38 EST 2009


On Jan 20, 12:54 pm, gert <gert.cuyk... at gmail.com> wrote:
> How do you convert s back to binary data in python 3 so I can put in a
> sqlite blob ?
> Is there a build in function or do I need to use binascii ?
> byte(s) or bin(s) would make more sense but can not figure it out ?

Can't imagine why you would do str(binary_data) especially if you want
it back again ... however:

According to the fabulous manual:

str([object[, encoding[, errors]]])
Return a string version of an object, using one of the following
modes:
[snip]
When only object is given, this returns its nicely printable
representation. For strings, this is the string itself. The difference
with repr(object) is that str(object) does not always attempt to
return a string that is acceptable to eval(); its goal is to return a
printable string.

Hmm looks like (1) we need to do the dreaded eval() and (2) there's no
guarantee it will work.

>>> for i in range(256):
...    blob = bytes([i])
...    if eval(str(blob)) != blob:
...       print(i, blob, str(blob), eval(str(blob)))
...
>>> # no complaints!

Looks like it's going to work, but you better be rather sure that you
trust the source.

HTH,
John



More information about the Python-list mailing list