1

I am needing to unserialize a string into an array in python just like php and then serialize it back.

2
  • this is what I am getting? File "serv.py", line 8, in ? zin_arr = pickle.loads(zin) File "/usr/lib/python2.4/pickle.py", line 1393, in loads file = StringIO(str) TypeError: expected read buffer, tuple found Commented Sep 12, 2009 at 0:10
  • @David that means your "zin" is a tuple, not a string. You should check to see what "zin" actually is. Commented Sep 12, 2009 at 2:10

4 Answers 4

1

If you mean PHP's explode, try this

>>> list("foobar")
['f', 'o', 'o', 'b', 'a', 'r']

>>> ''.join(['f', 'o', 'o', 'b', 'a', 'r'])
'foobar'
Sign up to request clarification or add additional context in comments.

Comments

0

What "serialized" the data in question into the string in the first place? Do you really mean an array (and if so, of what simple type?), or do you actually mean a list (and if so, what are the list's items supposed to be?)... etc, etc...

From the OP's comments it looks like he has zin, a tuple, and is trying to treat it as if it was, instead, a str into which data was serialized by pickling. So he's trying to unserialize the tuple via pickle.loads, and obviously that can't work -- pickle.loads wants an str (that's what the s MEANS), NOT a tuple -- it can't work with a tuple, it has even no idea of what to DO with a tuple.

Of course, neither do we, having been given zero indication about where that tuple comes from, why is it supposed to be a string instead, etc, etc. The OP should edit his answer to show more code (how is zin procured or fetched) and especially the code where zin is supposed to be PRODUCED (via pickle.dumps, I imagine) and how the communication from the producer to this would-be consumer is happening (or failing to happen;-).

Comments

0

A string is already a sequence type in Python. You can iterate over the string one character at a time like this:

for char in somestring:
    do_something(char)

The question is... what did you want to do with it? Maybe we can give more details with a more detailed question.

Comments

0

Take a look at the pickle module. It is probably what you're looking for.

import pickle

# Unserialize the string to an array
my_array = pickle.loads(serialized_data)

# Serialized back
serialized_data = pickle.dumps(my_array)

1 Comment

Hmm Maybe he did... not enough detail to know!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.