views:

263

answers:

4

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

A: 

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)
Evan Fosmark
I don't think he meant serializing by the word serialize...
Kieveli
Hmm Maybe he did... not enough detail to know!
Kieveli
A: 

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;-).

Alex Martelli
A: 

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.

Kieveli
A: 

If you mean PHP's explode, try this

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

>>> ''.join(['f', 'o', 'o', 'b', 'a', 'r'])
'foobar'
Unknown