dirty problem 3 lines

alex23 wuwei23 at gmail.com
Thu Sep 2 01:32:05 EDT 2010


bussiere bussiere <bussi... at gmail.com> wrote:
> it's just as it seems :
> i want to know how does ti works to get back an object from a string in python :
> pickle.loads("""b'\x80\x03]q\x00(K\x00K\x01e.'""") #doesn't work

Repeating the question without providing any further information
doesn't really help.

This is a byte string: b'\x80\x03]q\x00(K\x00K\x01e.'
As MRAB points out, you can unpickle a byte string directly.

This is a doc string: """note the triplet of double quotes"""
What you have is a doc string that appears to contain a byte string:
"""b'\x80\x03]q\x00(K\x00K\x01e.'"""

So the question for you is: what is putting the byte string inside of
a doc string? If you can stop that from happening, then you'll have a
byte string you can directly unpickle.

Now, if you _don't_ have control over whatever is handing you the dump
string, then you can just use string manipulation to reproduce the
byte string:

>>> dump = """b'\x80\x03]q\x00(K\x00K\x01e.'"""
>>> badump = dump[2:-1].encode()[1:]
>>> pickle.loads(badump)
[0, 1]

So:
 - dump[2:-1] strips off string representation of the byte string
(b'...')
 - .encode() turns it into an actual byte string
 - [1:] strips a unicode blank from the start of the byte string (not
entirely sure how that gets there...)

After that it should be fine to unpickle.





More information about the Python-list mailing list