How to convert a list to string and vice versa?

Asked

Viewed 4,092 times

1

I have a list: ('47075', 'josenestle', 'i need help') I do str1 = str(list) and have it in string.

However if you do list(str1) I do not recover my list.

I find no obvious solution, help would be very grateful.

2 answers

1

As commented, the answer presented does not solve the problem presented. If you have an object, you want to convert it to a string and later convert it back, you will need to use some serialization technique. In Python, the most common library for this is the pickle. To serialize, aka convert the object to a representation in string, the function is used pickle.dumps() and to convert back to the original object uses the function pickle.loads(), see documentation.

Whereas you own the object:

obj = ('47075', 'josenestle', 'i need help')

You can serialize it with:

obj_serialized = pickle.dumps(obj)

This way you will have a sequence of bytes representing its object. For example, the value of obj_serialized will be:

b'\x80\x03X\x05\x00\x00\x0047075q\x00X\n\x00\x00\x00josenestleq\x01X\x0b\x00\x00\x00i need helpq\x02\x87q\x03.'

After doing everything necessary with the object serialized, you can retrieve the object with:

obj_recuperado = pickle.loads(obj_serialized)

Getting:

('47075', 'josenestle', 'i need help')

It represents exactly the original object. Note that it is not the same object, but an object with the same value. You can prove this by checking his relationship to the original object:

print(obj == obj_recuperado)  # True
print(obj is obj_recuperado)  # False

-1

I found the answer!

>>> import ast
>>> x = u'[ "A","B","C" , " D"]'
>>> x = ast.literal_eval(x)
>>> x
['A', 'B', 'C', ' D']
>>> x = [n.strip() for n in x]
>>> x
['A', 'B', 'C', 'D']

Using "Ast.literal_eval" I have a safe way to evaluate strings literally.

  • That has nothing to do with your question, this solution could well do without literal_eval, at the end of the day you’re only removing spaces from the list elements. Still, I’m glad you solved them anyway

  • Yes I know, I was probably little explicit but I think it covers other hypotheses where the string is not so similar to the list. Thanks for the help anyway! Could we talk in private message form? I needed help with another @Miguel topic

  • seen @miguel I’ll email, obg

Browser other questions tagged

You are not signed in. Login or sign up in order to post.