简体   繁体   中英

python pack output in string format

I have done the following.

from struct import pack, unpack
t = 1234
tt = str(pack("<I", t))

printing tt gives \\xf3\\xe0\\x01\\x00 . How do I get original value of t back from tt?

I tried using unpacking the repr(tt) but that does not work out. How do I go about doing this?

>>> t=1234
>>> tt=pack('<I', t)
>>> tt
'\xd2\x04\x00\x00'
>>> unpack('<I', tt)
(1234,)

>>> ttt, = unpack('<I', tt) 
>>> ttt
1234

you are using the wrong package for serialization. the struct package is only useful for python code which interacts with C code.

for serialization into a string, you should use the pickle module .

import pickle

t = 1234
tt = pickle.dumps(t)
t = pickle.loads(tt)

unpack('<I', tt) will give you (1234,) .

repr doesn't work since it adds quotes to the string:

>>> repr('foo')
'"foo"'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM